Roadmap › LINQ — Language Integrated Query › Module: LINQ Basics
Lessons in this course (12)

2. Deferred vs immediate execution

Basic★ Must knowLesson 2 of 12
csharp
var numbers = new List<int> { 1, 2, 3 };
var evens = numbers.Where(n => n % 2 == 0);    // deferred: nothing executed yet
numbers.Add(4);
Console.WriteLine(string.Join(",", evens));     // 2,4  — query ran now, saw the added item

var snapshot = numbers.Where(n => n > 1).ToList();   // immediate: executed and stored
numbers.Add(10);
Console.WriteLine(snapshot.Count);                   // 3 — unaffected
Deferred (return a query)Immediate (execute now)
Where, Select, SelectMany, OrderBy, ThenBy, GroupBy, Join, Skip, Take, Distinct, Concat, ZipToList, ToArray, ToDictionary, ToHashSet, ToLookup, Count, Sum, Min, Max, Average, First, Single, Any, All, Contains, Aggregate

Interview tip: "Multiple enumeration" — iterating a deferred query twice runs it twice (two DB round trips for EF). Materialise once with ToList() if you need it again.