Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does IEnumerable.Any(Func) return a value?

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 }

When does Enumerable.Any() return the value? The second data element, or will it process every single element before returning true, in this instance?

like image 567
Andrew Gray Avatar asked Jun 01 '26 04:06

Andrew Gray


1 Answers

It returns as soon as it sees a matching element, or if none it processes the whole sequence.

For that reason it is better than using .Count(...) != 0 (also more readable and semantically meaningful).

like image 139
usr Avatar answered Jun 03 '26 17:06

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!