Let’s say that I have two arrays:
double[] array1 = new double [] {22.5, 15, 33.7, 42, 17, 7.5, 3.5, 1, 17.5, 7.7, 5}
int[] idx = new int[] { 1, 4, 5, 8};
Now I need to generate new array that will have values from array1, but only this with indexes matching idx. So, in this case it should be:
{15, 17, 7.5, 17.5}
I’m more experienced in MATLAB and I was expecting that I can do simple:
array2=array1[idx];
But as far as I found the C# [] indexing works only for one element queries. So, what is recommended way to do this?
>Solution :
Well you could do it "long-hand":
double[] array2 = new double[idx.Length];
for (int i = 0; i < idx.Length; i++)
{
array2[i] = array1[idx[i]];
}
Or use LINQ:
double[] array2 = idx.Select(i => array1[i]).ToArray();
Both will do the job. There’s no "shortcut" available. You could potentially create your own class to do custom indexing if you really wanted to, but I’d just use one of the approaches above.