IEnumerable.Any(Func)何时返回值? [英] When does IEnumerable.Any(Func) return a value?
问题描述
最近,我在与我合作的代码库中看到了一些代码,ReSharper提供了将其重构为collection.Any(Func< bool >)
的代码.
I recently saw a bit of code in a codebase I work with, where ReSharper offered to refactor it to collection.Any(Func< bool >)
.
我想知道这样做对性能的影响.假设我有一个看起来像这样的电话:
I'm wondering about the performance impacts of this. Say I have a call that looks like this:
bool hasEvenValue = collection.Any(i => (i % 2) == 0);
...还有看起来像这样的数据...
...And data that looks like this...
{ 1, 2, 3, 5, 3, 5, 1, 3, 5, 2 }
Enumerable.Any()何时返回值?在这种情况下,第二个数据元素,还是会在返回true之前处理每个单个元素?
When does Enumerable.Any() return the value? The second data element, or will it process every single element before returning true, in this instance?
推荐答案
只要看到匹配的元素,它就会立即返回;否则,它会处理整个序列.
It returns as soon as it sees a matching element, or if none it processes the whole sequence.
因此,它比使用.Count(...) != 0
(也更具可读性和语义意义)更好.
For that reason it is better than using .Count(...) != 0
(also more readable and semantically meaningful).
这篇关于IEnumerable.Any(Func)何时返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!