Randolph
Randolph

Reputation: 37

LINQ to create list of strings from indexes stored in int[]

This is what I have:

int[] indexes; // it contains indexes that are "good"
string[] words; // many words
List<string> result;

And I would like to do this code:

for (int i = 0; i < words.Count(); ++i)
    if (indexes.Contains(i))
        result.Add(words[i]);

In only one line, by LINQ I guess :) How?

Upvotes: 0

Views: 131

Answers (2)

Guvante
Guvante

Reputation: 19203

Assuming a distinct set of indexes. We can just grab each word rather than starting from the words and finding matching indexes.

List<string> result = indexes.Select(i => words[i]).ToList();

Note that this version is much faster assuming indexes is smaller than words. (100 indexes and 20,000 words would be 20 million operations in yours and 100 in mine).

Upvotes: 7

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Well, not one liner but:

result = Enumerable.Range(0, words.Count())
      .Where(indexes.Contains)
      .Select(idx => words[idx])
      .ToList();

Upvotes: 1

Related Questions