LINQ deferred execution

A LINQ query is a recipe, not a result. It runs each time you enumerate it, against the data as it is then.

Time runs on enumerationSpace O(1) until materialisedCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Where returns an object that remembers the source and the filter. No element is tested until something asks for results. ToList, ToArray, Count and foreach are what trigger the work.

Code

var nums = new List<int> { 1, 2, 3 };
var big = nums.Where(n => n > 1);   // nothing runs yet
nums.Add(4);
foreach (int n in big) Console.Write(n);   // 234
var snap = big.ToList();            // runs now and stores the results
nums.Add(5);
Console.Write(snap.Count);          // still 3

Tips

In the .NET library

Where, Select, OrderBy, Skip and Take are deferred. ToList, ToArray, ToDictionary, Count, First, Any and Sum execute immediately.