LINQ 从存储在 int[] 中的索引创建字符串列表

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

这是我的:

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

我想做这个代码:

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

只有一行,我猜是 LINQ :) 怎么样?

好吧,不是一个班轮而是:

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

假设有一组不同的索引。我们可以只抓取每个单词,而不是从单词开始寻找匹配的索引。

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

请注意,假设索引比单词小,这个版本要快得多。 (100 个索引和 20,000 个单词在你的是 2000 万次操作,在我的是 100 次)。