Explain deferred execution in LINQ.
4 minintermediate.NETLINQdeferred-execution
Quick Answer
Deferred (lazy) execution means a LINQ query isn't run when defined — it builds an expression that executes only when enumerated (e.g., by `foreach`, `ToList`, `Count`). This lets queries compose efficiently and reflect the latest source data, but it also means the query runs every time you enumerate it and can cause multiple round-trips or re-evaluation. Materialize with `ToList()`/`ToArray()` when you need a snapshot or want to enumerate once.
Detailed Answer
Deferred Execution means LINQ queries are not executed when they are defined, but only when the results are actually enumerated.
How it works:
- Query definition creates an execution plan
- Actual execution happens when you iterate (foreach, ToList(), Count(), etc.)
- Query is re-executed each time you enumerate it
- Benefits: improved performance, fresh data on each execution
var numbers = new List { 1, 2, 3, 4, 5 };
// Query is DEFINED but NOT executed
var query = numbers.Where(n => n > 2);
Console.WriteLine("Query defined");
// NOW the query executes (deferred execution)
foreach (var num in query)
{
Console.WriteLine(num); // Outputs: 3, 4, 5
}
// Modifying source affects query results
numbers.Add(6);
numbers.Add(7);
// Query executes AGAIN with new data
foreach (var num in query)
{
Console.WriteLine(num); // Outputs: 3, 4, 5, 6, 7
}
// Force immediate execution
var immediateResult = numbers.Where(n => n > 2).ToList();
numbers.Add(8); // This won't affect immediateResult
Operations with Immediate Execution:
ToList(),ToArray(),ToDictionary()Count(),Sum(),Average(),Max(),Min()First(),Single(),Last()Any(),All()
Operations with Deferred Execution:
Where(),Select(),OrderBy()Skip(),Take(),GroupBy()Join(),SelectMany()