Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the recommended way to operate on C# arrays by multiple indexes?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading