Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string[] elements with index of int[] indices

Tags:

c#

.net

lambda

linq

I have a string[], and want to get the elements of the string[] that has an index, of which i know exist, specified in an int[].

string[] stringArray = { "a", "b", "c", "d", "e", "f", "g" };
int[] indices = { 1, 2, 4, 6 };

From this, I am trying to get a string[] containing { "b", "c", "e", "g" }. Preferably using a lambda expression. How would I do this?

like image 614
sshow Avatar asked Nov 30 '22 03:11

sshow


2 Answers

indices.Select(i => stringArray[i]);
like image 30
Kendall Frey Avatar answered Dec 12 '22 13:12

Kendall Frey


One way you can do it is like this.

string[] result = indices.Select(i => stringArray[i]).ToArray()
like image 111
recursive Avatar answered Dec 12 '22 14:12

recursive