使用LINQ,如何在特定索引中选择项目?

Joh*_*ell 4 c# linq ienumerable

如果我有一个IEnumerable<Foo> allFoos和一个IEnumerable<Int32> bestFooIndexes,我怎么能得到一个新的IEnumerable<Foo> bestFoos包含指定索引的Foo条目?allFoosbestFooIndexes

Eli*_*sha 12

var bestFoos = bestFooIndexes.Select(index => allFoos.ElementAt(index));
Run Code Online (Sandbox Code Playgroud)

如果你担心性能而且收藏量很大:

List<Foo> allFoosList = allFoos.ToList();
var bestFoos = bestFooIndexes.Select(index => allFoosList[index]);
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 11

以利沙的回答肯定会奏效,但效率可能非常低......这取决于allFoos实施的内容.如果它是一个实现IList<T>,ElementAt将是高效的 - 但如果它实际上是(例如)LINQ to Objects查询的结果,那么将为每个索引重新运行查询.所以编写它可能更有效:

var allFoosList = allFoos.ToList();
// Given that we *know* allFoosList is a list, we can just use the indexer
// rather than getting ElementAt to perform the optimization on each iteration
var bestFoos = bestFooIndexes.Select(index => allFoosList[index]);
Run Code Online (Sandbox Code Playgroud)

当然,只有在需要时你才能做到这一点:

IList<Foo> allFoosList = allFoos as IList<Foo> ?? allFoos.ToList();
var bestFoos = bestFooIndexes.Select(index => allFoosList[index]);
Run Code Online (Sandbox Code Playgroud)