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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With