Does chaining LINQ statements result in multiple iterations?
For example, let's say I want to filter my data with a where clause, and then on the matches do a sum:
int total = data.Where(item => item.Alpha == 1 && item.Beta == 2)
.Sum(item => item.Qty);
Does this result in a single interation of the data, such that it would be equivalent to this?
int total = 0;
foreach (var item in data)
if (item.Alpha == 1 && item.Beta == 2)
total += 1;
Or, does it iterate over data
once, and the results of the where
a second time to do the sum?
The statements in LINQ are streamed, so Where
does not actually run until Sum
enumerates through its values. This means the items from data
will effectively be enumerated a single time.
Basically, the Where
method creates a new IEnumerable<T>
, but doesn't actually enumerate through data
. Sum
does a foreach
over the IEnumerable<T>
from Where
, which in turn pulls items through the Where
sequence one at a time.
Yes, that LINQ query will cause only one iteration over source collection.
How it works? Sum
asks for one element at the time and so does Where
(on source collection). So when Sum
need next element, it calls MoveNext
on Enumerator<T>
taken from Where
, which is implemented as following:
foreach(var item in source)
if(predicate(item))
yield return item;
To understand it more you should read about iterators: Iterators (C# and Visual Basic)
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