Reputation: 3
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.`
Upvotes: 0
Views: 80
Reputation: 56716
if you can use LINQ, here is a way:
string[] someWords = indices.Select(index => myWords[index]).ToArray();
Upvotes: 4
Reputation: 73502
Not sure this is what you're asking about.
string[] myWords = {"foo", "overflow", "bar", "stack"};
int[] indices = {3, 1};
string[] someWords = indices.Select(x=> myWords[x]).ToArray();
Upvotes: 1