How to select elements from an array using an array of indices with Linq?

How to select elements from an array using an array of indices with Linq?

The following code works:

String[] A = new String[] { "one", "two", "three", "four" }; int[] idxs = new int[] { 1, 3 }; String[] B = new String[idxs.Length]; for (int i = 0; i < idxs.Length; i++) { B[i] = A[idxs[i]]; } System.Diagnostics.Debug.WriteLine(String.Join(", ", B)); 

output:

  two, four 

Is there a LINQ (or other single line) way to get rid of the for loop?

+6
source share
2 answers

You can use it with Select with your index and your A[index] Like:

 String[] A = new String[] { "one", "two", "three", "four" }; int[] idxs = new int[] { 1, 3 }; var result = idxs.Select(i => A[i]).ToArray(); foreach(var s in result) Console.WriteLine(s); 

The output will be:

 two four 

Here is the DEMO .

+5
source

The LINQ method will be as follows:

 var b = idxs.Select(x => A[x]).ToArray(); 
+14
source

All Articles