Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

linq

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?

like image 692
tdc Avatar asked Mar 20 '13 12:03

tdc


People also ask

Can LINQ query work with array?

LINQ allows us to write query against all data whether it comes from array, database, XML etc.

Can you access an array element by referring to the index?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you find the index of an element in LINQ?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

How does select work in LINQ?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.


1 Answers

A LINQ way would be this:

var b = idxs.Select(x => A[x]).ToArray();
like image 70
Daniel Hilgarth Avatar answered Oct 11 '22 14:10

Daniel Hilgarth