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?
LINQ allows us to write query against all data whether it comes from array, database, XML etc.
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.
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.
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.
A LINQ way would be this:
var b = idxs.Select(x => A[x]).ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With