tags:

views:

47

answers:

2

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 is 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.

+7  A: 

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 Skeet
Ah, okay - I'd wondered if it was smart enough to stop as soon as the head became false, knowing that the result would then always be false.Thanks!
Jon Artus
+2  A: 

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.

Benjamin Podszun
Thanks for the extras - I'd been using aggregate to do some little string concatenations and other transformations, and found myself automatically writing Option 2, before realising that Any() was a far easier option.
Jon Artus