8

How do I select items from an array using an array of indices with Linq?

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 way (or other one-liner) to get rid of the for loop?

1
  • 2
    Why do you want to get rid of the for loop? Is it slow? Hard to read? Commented Mar 20, 2013 at 12:29

2 Answers 2

16

A LINQ way would be this:

var b = idxs.Select(x => A[x]).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

9

You can use it with Select 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);

Output will be:

two
four

Here is a DEMO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.