Search code examples
c#arraysindices

Accessing single-dimensional array entries with index array


I am trying to access elements in a single-dimensional "data" array (string or double) via another array that contains the indices I wish to extract:

string[] myWords = {"foo", "overflow", "bar", "stack"};
int[] indices = {3, 1};

string[] someWords = myWords[indices]; // Extract entries number three and one.

The last line is refused by the compiler. What I'd like to see is someWords == {"stack", "overflow"}.

As far as I know, this works in Matlab and Fortran, so is there any nice and elegant way to do this for arrays in C#? Lists are fine, too.

Array.GetValue(int[]) like in this question does not work in my case, since this method is for multidimensional arrays only.`


Solution

  • if you can use LINQ, here is a way:

    string[] someWords = indices.Select(index => myWords[index]).ToArray();