2

My title question is a little vague, since it's hard to ask, but my situation is this:

I have an array of ints, which are indices into a separate collection of objects.

The array looks like this:

int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };

Each of these indices corresponds to an object at that index in a collection I have.

I want to be able to build a new collection of these objects using the indices in my array.

How would I do that using some LINQ functions?

2 Answers 2

5
int[] indices = { 0, 2, 4, 9, 10, 11, 13 };
string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" };

IEnumerable<string> results = indices.Select(s => strings[s]);

// or List<string> results = indices.Select(s => strings[s]).ToList();

foreach (string result in results) // display results
{
    Console.WriteLine(result);
}

Of course change strings etc to your collection of objects.

Sign up to request clarification or add additional context in comments.

Comments

4

Something like this should work:

List<int> items = Enumerable.Range(1,100).ToList();
int[] indices = { 0, 2, 4, 9, 10, 11, 13, /* more (non-)sequential indices */ };
var selectedItems = indices.Select( x => items[x]).ToList();

Basically for each index in your collection of indices you are projecting to the corresponding item in your items collection (whatever type those items are) using the indexer.

If your target collection is just an IEnumerable<SomeType> than you can alternatively use ElementAt() instead of an indexer:

var selectedItems = indices.Select(x => items.ElementAt(x)).ToList();

1 Comment

Thanks for the response. I wish I could accept multiple answers, sometimes I feel bad not being able to accept every single working answer. :(

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.