C# › LINQ

What is 'deferred execution' in LINQ, and how does it differ from calling .ToList() or .ToArray() immediately?

Intermediate

Answer

Most LINQ methods (Where, Select, OrderBy, etc.) build up a QUERY DEFINITION without actually executing it — the query only runs when you actually ITERATE the results (via foreach, ToList(), ToArray(), etc.), meaning the underlying data source is re-evaluated fresh EVERY time you enumerate a deferred query, reflecting any changes made since it was defined.
var query = numbers.Where(n => n > 5); // NOT executed yet, just defined
numbers.Add(10); // this NEW element IS included, since the query hasn't run yet
var results = query.ToList(); // NOW it actually executes, includes the newly added 10
Real-world example Understanding a subtle bug where a LINQ query's results unexpectedly change because the underlying collection was modified before the query was actually enumerated.

Common follow-ups: Which specific LINQ methods (like Count() or ToList()) force IMMEDIATE execution instead of deferring?