条件为真时,LINQ to对象是否停止处理Any()? [英] Does LINQ to objects stop processing Any() when condition is true?

查看:52
本文介绍了条件为真时,LINQ to对象是否停止处理Any()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

bool invalidChildren = this.Children.Any(c => !c.IsValid());

此类包含具有 IsValid()方法的子对象的集合.假设 IsValid()方法是一个处理器密集型任务.在遇到第一个子对象(其中的 IsValid() false )之后,理论上可以停止处理,因为结果永远不会变为真.LINQ to对象在第一个 IsValid()= false (像逻辑与)之后实际上停止评估了吗?还是继续评估所有子对象?

This class has a collection of child objects that have an IsValid() method. Suppose that the IsValid() method is a processor intensive task. After encountering the first child object where IsValid() is false, theoretically processing can stop because the result can never become true. Does LINQ to objects actually stop evaluating after the first IsValid() = false (like a logical AND) or does it continue evaluating all child objects?

很明显,我可以将其放入foreach循环中并中断第一个无效结果,但是我只是想知道LINQ对对象是否也足够聪明来做到这一点.

Obviously I could just put this in a foreach loop and break on the first invalid result, but I was just wondering if LINQ to objects is smart enough to do this as well.

感谢您的回答,出于某种原因,我不希望自己在MSDN上进行查找.

Thanks for the answers, for some reason I didn't think to look it up on MSDN myself.

推荐答案

是的.一旦找到匹配项,就满足标准. All 的相似之处在于,它会检查所有项目,但如果不匹配,则会立即结束.

Yes it does. As soon as it finds a match, the criteria is satified. All is similar in that it checks all items but if one doesn't match it ends immeditately as well.

存在的工作方式也相同.

任何

确定结果后立即停止源枚举.

The enumeration of source is stopped as soon as the result can be determined.

存在

当前List的元素分别传递给Predicate委托,并在找到匹配项时停止处理.

The elements of the current List are individually passed to the Predicate delegate, and processing is stopped when a match is found.

全部

确定结果后立即停止源枚举.

The enumeration of source is stopped as soon as the result can be determined.

等...

这篇关于条件为真时,LINQ to对象是否停止处理Any()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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