0

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.`

3
  • That looks like syntax that would work in a language from a different paradigm. In C#, array operations are much more manual; the LINQ answer works (a library doing the job) or you could implement it explicitly as a loop over the values in indices with a manually-constructed array containing the results. Commented Feb 10, 2014 at 18:00
  • 1
    Of course I could do it manually, but I was specifically looking for an elegant one-liner. Commented Feb 11, 2014 at 2:57
  • I'm not sure "elegant one-liner" isn't an oxymoron :). Commented Mar 1, 2014 at 10:59

2 Answers 2

4

if you can use LINQ, here is a way:

string[] someWords = indices.Select(index => myWords[index]).ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that looks exactly like the thing I was looking for! Will try it as soon as I get back to the code.
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.