Aggregate vs. Any, for scanning objects such as IEnumerable<bool>
Just wondered if any LINQ guru might be able to shed light on how Aggregate and Any work under the hood.
Imagine that I have an IEnumerable which stores the results of testing an array for a given condition. I want to determine whether any element of the array i开发者_JAVA百科s false. Is there any reason I should prefer one option above the other?
IEnumerable<bool> results = PerformTests();
return results.Any(r => !r); //Option 1
return results.Aggregate((h, t) => h && t); //Option 2
In production code I'd tend towards 1 as it's more obvious but out of curiosity wondered whether there's a difference in the way these are evalulated under the hood.
Yes, definitely prefer option 1 - it will stop as soon as it finds any value which is false.
Option 2 will go through the whole array.
Then there's the readability issue as well, of course :)
Jon beat me again, but to add some more text:
Aggregate always needs to consume the whole IEnumerable<T>
, because that's exactly what it's supposed to do: To generate a dataset from your (complete) source.
It's the "Reduce" in the well-known Map/Reduce scenario.
精彩评论