是否有更有效的LINQ语句可以反向搜索List T中的条件? [英] Is there a more efficient LINQ statement to reverse-search for a condition in a List<T>?

查看:124
本文介绍了是否有更有效的LINQ语句可以反向搜索List T中的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试针对List<T>编写LINQ语句,该语句从该列表的末尾向后搜索条件,但在指定的"T"项处停止.

We're trying to write a LINQ statement against a List<T> that searches backwards from the end of that list for a condition, but which stops at a specified 'T' item.

例如,如果列表中有1000个项目,并且限制"项目位于位置995(索引994),则我们只想在最后六个项目中搜索测试条件.我们需要这是尽可能的高性能.

For instance, if the list has 1000 items and the 'limit' item is at position 995 (index 994), then we only want to search the last six items for the test condition. We need this to be as high-performance as possible.

但是,要使用LINQ,我们知道的唯一方法是获取'limit'项目的现有索引,这很昂贵,然后在整个源集合上运行带有索引的Select,这同样也很昂贵,就像这样...

However, to use LINQ, the only way we know is to get the existing index of the 'limit' item, which is expensive, then run a Select with index over the entire source collection, which also is expensive, like this...

// Assume limitItem is of type Foo and sourceList is of type List<Foo> 

var limitIndex = sourceList.IndexOf(limitItem);
var sourceListWithIndex = sourceList.Select( (Foo, Index) => new { Foo, Index } );

var fooWithIndex = sourceListWithIndex
    .LastOrDefault(item =>
        (item.Foo.SomTestValue == true)
        &&
        (item.Index >= limitIndex) );

那么有什么更简单的方法告诉Linq'停止枚举您是否已检查过该项目',还是我必须自己在基于索引的循环中手动完成操作,而根本不使用LINQ?

So is there an easier way to tell Linq 'Stop enumerating if you've checked this item', or will I have to manually do it myself in an index-based loop and not use LINQ at all?

推荐答案

您不需要任何一个.

sourceList.Reverse()
          .TakeWhile(o => o != limitItem)
          .FirstOrDefault(o => ...);

由于推迟执行(并假定sourceList实现了IList<T>),所以这将使列表的一部分仅重复一次.

Thanks to deferred execution (and assuming sourceList implements IList<T>), this will iterate part of the list exactly once.

这篇关于是否有更有效的LINQ语句可以反向搜索List T中的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆