gpt4 book ai didi

c# - Any() 会在成功时停止吗?

转载 作者:太空狗 更新时间:2023-10-30 00:02:47 24 4
gpt4 key购买 nike

更具体地说:Linq 扩展方法 Any(IEnumerable collection, Func predicate) 是否会在 predicate 对某个项目产生 true 时停止检查集合的所有剩余元素?

因为我根本不想花太多时间来弄清楚我是否需​​要做真正昂贵的部分:

if(lotsOfItems.Any(x => x.ID == target.ID))
//do expensive calculation here

因此,如果 Any 总是检查源代码中的所有项目,这可能最终会浪费时间,而不是继续:

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

因为我很确定 FirstOrDefault 确实在得到结果后返回,并且只有在它没有在收藏。

有没有人知道 Any 的内部工作原理,或者有人可以为这种决定提出解决方案?

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

if(!lotsOfItems.All(x => x.ID != target.ID))

因为一旦条件第一次返回 false 就应该停止,但我不确定这一点,所以如果有人也能阐明这一点,我们将不胜感激。

最佳答案

正如我们从 source code 中看到的那样, :

 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;
}

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

also:a colleague suggested something along the lines of

if(!lotsOfItems.All(x => x.ID != target.ID)) since this is supposed to stop once the conditions returns false for the first time but i'm not sure on that, so if anyone could shed some light on this as well it would be appreciated :>]

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

补充说明:
如果您使用 Linq to objects,则上述情况成立。如果您正在使用 Linq to Database,那么它将创建一个查询并针对数据库执行它。

关于c# - Any() 会在成功时停止吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30259730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com