Any()是否会成功停止?

gar*_*arg 4 c# linq

更具体一点:Any(IEnumerable collection, Func predicate)一旦谓词对一个项目产生了真值,Linq扩展方法是否会停止检查集合中的所有剩余元素?

因为我不想花很多时间来弄清楚我是否需​​要做真正昂贵的零件:

if(lotsOfItems.Any(x => x.ID == target.ID))
    //do expensive calculation here
Run Code Online (Sandbox Code Playgroud)

因此,如果Any始终检查源中的所有项目,这可能最终浪费时间而不是仅仅是:

var candidate = lotsOfItems.FirstOrDefault(x => x.ID == target.ID)
if(candicate != null)
     //do expensive calculation here
Run Code Online (Sandbox Code Playgroud)

因为我很确定它FirstOrDefault一旦得到结果就会返回,只有Enumerable在集合中没有找到合适的条目时才会继续通过整体.

有没有Any人有关于这种决定的内部运作的信息,或者有人可以提出解决方案吗?

此外,一位同事提出了类似的建议:

if(!lotsOfItems.All(x => x.ID != target.ID))
Run Code Online (Sandbox Code Playgroud)

因为这应该是一旦条件第一次返回假就停止但是我不确定,所以如果有人能够对此有所了解,那将是值得赞赏的.

Far*_*yev 8

正如我们从源代码中看到的那样,:

 internal static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
            foreach (T element in source) {
                if (predicate(element)) {
                    return true; // Attention to this line
                }
            }
            return false;
        }
Run Code Online (Sandbox Code Playgroud)

Any() 是确定序列的任何元素是否满足LINQ条件的最有效方法.

还有:一位同事提出了类似的建议

if(!lotsOfItems.All(x => x.ID!= target.ID))因为这应该在条件第一次返回false时停止但是我不确定,所以如果有人可以放弃一些对此有所了解,我们将不胜感激:>]

All()确定序列的所有元素是否满足条件.因此,只要可以确定结果,就会停止源的枚举.

附加说明:
如果您使用Linq对象,则上述情况属实.如果您使用Linq to Database,那么它将创建一个查询并将对数据库执行它.