C# Reference ยท LINQ
LINQ deferred execution
How LINQ deferred execution works in C#: which operators are lazy, when a query actually runs, captured variables, repeated runs and how to snapshot results.
Most LINQ operators do not do their work when you call them. Where(), Select(), OrderBy() and friends only build a description of a pipeline and return an object that remembers the source and the lambdas. The work happens later, when something enumerates the result: a foreach loop, ToList(), Count(), First() and so on. This is called deferred execution.
The opposite is immediate execution. Operators that return a single value or a materialized collection (ToList(), ToArray(), Count(), Sum(), First(), ToDictionary()) run the whole pipeline right away. Knowing which is which explains most surprising LINQ behavior: queries that see changed data, lambdas that run twice, and exceptions that appear far from where the query was written.
var query = numbers.Where(n => n > 3); // nothing runs yet numbers.Add(10); // the query will see this var snapshot = query.ToList(); // runs now, once
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
There is no syntax to learn: deferred execution is a property of each operator. The table sorts the common ones.
| Kind | Operators |
|---|---|
| Deferred, streaming (one element at a time) | Where, Select, SelectMany, Take, Skip, TakeWhile, SkipWhile, Concat, Zip, Cast, OfType, Index |
Deferred, buffering (reads the whole source on the first MoveNext) |
OrderBy, Order, Reverse, GroupBy, Join, GroupJoin, Distinct, Except, Intersect, Union, CountBy, AggregateBy |
| Immediate | ToList, ToArray, ToDictionary, ToHashSet, ToLookup, Count, Sum, Min, Max, Average, Aggregate, Any, All, Contains, First, Single, Last, ElementAt, SequenceEqual |
| Static generators (deferred) | Range, Repeat, Empty |
Errors / timing: argument checks (such as a null source) usually happen at the call. Exceptions thrown by your lambdas, by the source, or by the data (division by zero, bad cast) happen during enumeration.
Usage notes
- Every enumeration re-runs the pipeline. Calling
Count()thenToList()on the same query evaluates it twice, including any expensive or side-effecting lambda. Materialize once withToList()orToArray()when you need the results more than once. - Queries see current data. The source is read at enumeration time, so changes made after the query was written appear in its results. A snapshot with
ToList()freezes the data. - Modifying a collection while enumerating it throws
InvalidOperationExceptionforList<T>and most built-in collections. Materialize first, then change the original. - Closures read variables, not values. A lambda uses the variable's value at the time it runs. In loops, capture a copy into a local variable if you need the current value.
- Streaming makes big or endless sources possible.
Range(1, int.MaxValue).Where(...).Take(5)is fine; adding a buffering operator such asOrderBy()beforeTake()is not. - Keep side effects out of lambdas. Logging, mutation and I/O inside
Select()orWhere()run an unpredictable number of times. Use aforeachfor effects. - Returning queries from methods hands the deferral to the caller; if the underlying resource (a
StreamReader, a database context) is disposed by then, enumeration fails. Return a list in that case. - Iterator methods with
yield returnare deferred too; their argument checks run late unless you split them into a wrapper plus a local iterator function.