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.
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 3Tips
- Enumerating the same query twice does the work twice. If the source is a database or an expensive computation, materialise once with ToList.
- Deferred queries see later changes to the source, which is either a feature or a bug depending on what you expected.
In the .NET library
Where, Select, OrderBy, Skip and Take are deferred. ToList, ToArray, ToDictionary, Count, First, Any and Sum execute immediately.