Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does chaining LINQ statements result in multiple iterations?

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?

like image 291
Matt Avatar asked Sep 16 '25 14:09

Matt


2 Answers

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.

like image 72
Reed Copsey Avatar answered Sep 19 '25 04:09

Reed Copsey


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)

like image 22
MarcinJuraszek Avatar answered Sep 19 '25 04:09

MarcinJuraszek