LINQ任何VS FirstOrDefault的表现!= NULL [英] Performance of LINQ Any vs FirstOrDefault != null

查看:756
本文介绍了LINQ任何VS FirstOrDefault的表现!= NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有在一个开源项目(OSP)code我奉献,在那里有一个,如果集合中的元素满足一定的条件,以确定多个地方。

There are multiple places in an Open Source Project (OSP) code I contribute, where it has to be determined if an element in a collection satisfies a certain condition.

我见过的使用LINQ前pression 任何(拉姆达前pression)在某些情况下和 FirstOrDefault的(拉姆达前pression)!= NULL 于别人,但从来没有一个关于它的想法。

I've seen the use of LINQ expression Any(lambda expression) in some cases and FirstOrDefault(lambda expression) != null in others but never given a thought about it.

我现在已经达到一个地步,我必须做一些迭代通过查询到DB做收藏,希望优化运行。

I have reached now a point where I have to do some iterations to collections made from queries to a DB and want to optimize the runtime.

所以我想通了 FirstOrDefault(拉姆达前pression)!= NULL 应该比任何(拉姆达前pression快),对吧?

So I figured that FirstOrDefault(lambda expression) != null should be faster than Any(lambda expression),right?

FirstOrDefault(拉姆达前pression)!= NULL 的情况下,当它发现满足条件的元素(更糟糕的迭代(可能)停止的情况下它通过整个集合,并返回迭代)。

In the case of FirstOrDefault(lambda expression) != null, the iteration (probably) stops when it finds an element that satisfies the condition (worse case scenario it iterates through the entire collection and returns null).

在的情况下,任何(拉姆达前pression)我想,迭代持续到集合的末尾,即使满足条件的元素找到。

In the case of Any(lambda expression) I imagine that the iteration continues to the end of the collection even if an element that satisfies the condition is found.

编辑:杰克逊提到教皇和链接相关的MSDN文章上面是不正确的。

The above is not true as Jackson Pope mentioned and linked the related MSDN article.

是我的想法正确的还是我失去了一些东西?

Are my thoughts correct or am I missing something?

推荐答案

枚举的任何()只要它找到一个匹配的项目,以及停止:

The enumeration in Any() stops as soon as it finds a matching item as well:

<一个href=\"http://msdn.microsoft.com/en-us/library/bb534972.aspx\">http://msdn.microsoft.com/en-us/library/bb534972.aspx

我期望的表现非常相似。请注意, FirstOrDefault 版本不会与价值类型的采集工​​作(因为defaul不为空),但任何版本会。

I would expect the performance to be very similar. Note that the FirstOrDefault version won't work with a collection of value types (since the defaul isn't null) but the Any version would.

这篇关于LINQ任何VS FirstOrDefault的表现!= NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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