.NETEasy
What is the difference between deferred and immediate execution in LINQ?
Deferred execution — the query is not run until you enumerate the result.
var query = numbers.Where(n => n > 10); // nothing runs yet
foreach (var n in query) Console.WriteLine(n); // NOW it runs
foreach (var n in query) Console.WriteLine(n); // runs AGAIN
Each enumeration re-executes the entire pipeline. Cheap if the source is in memory, but a database query is re-issued every time.
Immediate execution — forces materialisation, captures the result.
var list = numbers.Where(n => n > 10).ToList(); // executes ONCE, stores in memory
foreach (var n in list) Console.WriteLine(n);
foreach (var n in list) Console.WriteLine(n); // same materialised list, no re-execution
Methods that trigger immediate execution: ToList, ToArray, ToDictionary, ToHashSet, First, Single, Count, Any, Max, Sum, Aggregate.
The trap: modifying the source after building a deferred query changes the result on next enumeration.
var q = list.Where(x => x > 5);
list.Add(10);
foreach (var x in q) Console.WriteLine(x); // 10 is included
Rule: call .ToList() as soon as you stop composing the query. Deferred is a feature when you want it, a bug when you don't.