Get strings [] with index index int []

I have a string[] and want to get the string[] elements with the index that I know about, specified in 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" } . It is preferable to use a lambda expression. How can I do it?

+4
source share
6 answers

One way to do this is this.

 string[] result = indices.Select(i => stringArray[i]).ToArray() 
+10
source
 indices.Select(i => stringArray[i]); 
+6
source
 stringArray.Where((x,index) => indices.Contains(index)); 
+3
source
 foreach( int i in indices){ string s = stringArray[i] //DO stuff } 
+1
source

LINQ: var result = from indice in indices select stringArray[indice]
LAMBDA EXPRESSION: var result = indices.Select(i => stringArray[i])

+1
source

Something like that:

 var result= ( from str in stringArray.Select ((a,i) =>new {a,i}) where indices.Contains(str.i) select str ); 
+1
source

Source: https://habr.com/ru/post/1401837/


All Articles