C# LINQ deferred execution
last modified November 15, 2026
This tutorial explains LINQ deferred execution in C#: when a query actually runs, which operators run immediately, how streaming differs from buffering, and what problems repeated enumeration and captured variables cause.
Most LINQ operators use deferred execution. Calling
Where or Select does not process any data; it
returns an object that describes the query. The work is done later, when the
result is enumerated, for instance by a foreach loop or by a
method such as ToList. Each enumeration runs the query again
against the current state of the source.
LINQ operators fall into three groups:
| Group | Examples | Behavior |
|---|---|---|
| Deferred, streaming | Where, Select, Take, Skip, Distinct |
produce elements one at a time while the source is read |
| Deferred, buffering | OrderBy, GroupBy, Reverse, Join (inner sequence) |
read the whole source when the first element is requested |
| Immediate | Count, Sum, First, Any, ToList, ToArray, ToDictionary |
run the query when called and return a value or a collection |
A query runs when it is enumerated
In the first example, the predicate of Where prints each value
it checks. This shows exactly when the filtering happens.
List<int> numbers = [1, 2, 3, 4, 5];
var query = numbers.Where(n =>
{
Console.WriteLine($" checking {n}");
return n % 2 == 0;
});
Console.WriteLine("query created");
numbers.Add(6);
Console.WriteLine("enumerating:");
foreach (var n in query)
{
Console.WriteLine($"got {n}");
}
Console.WriteLine(query.GetType().Name);
We create a query, add an element to the source, and enumerate the query.
var query = numbers.Where(n =>
{
Console.WriteLine($" checking {n}");
return n % 2 == 0;
});
Nothing is checked yet. Where only stores the source and the
predicate in an iterator object.
numbers.Add(6);
The element is added after the query was created, but it appears in the results, because the list is read only during enumeration.
Console.WriteLine(query.GetType().Name);
The query is an instance of an internal iterator class optimized for lists.
It implements IEnumerable<int>; the output shows that each
element is checked and returned before the next one is read.
$ dotnet run query created enumerating: checking 1 checking 2 got 2 checking 3 checking 4 got 4 checking 5 checking 6 got 6 ListWhereIterator`1
Deferred and immediate operators
Operators that return a single value or a new collection run the query immediately. Their result does not change when the source changes later.
List<string> fruits = ["apple", "banana", "cherry", "date"];
var longNames = fruits.Where(f => f.Length > 5);
int count = fruits.Count(f => f.Length > 5);
List<string> snapshot = longNames.ToList();
fruits.Add("elderberry");
fruits.Add("fig");
Console.WriteLine($"deferred: {string.Join(", ", longNames)}");
Console.WriteLine($"Count: {count}");
Console.WriteLine($"ToList: {string.Join(", ", snapshot)}");
We create a deferred query, a count, and a list snapshot, and then modify the source.
var longNames = fruits.Where(f => f.Length > 5); int count = fruits.Count(f => f.Length > 5); List<string> snapshot = longNames.ToList();
Count and ToList run at once. The
longNames query is run later, when it is passed to
string.Join.
fruits.Add("elderberry");
fruits.Add("fig");
Only the deferred query sees the new elderberry element.
$ dotnet run deferred: banana, cherry, elderberry Count: 2 ToList: banana, cherry
Streaming and buffering
Streaming operators pass each element through the whole chain before reading the next one. Buffering operators must see all elements before they can return the first one.
int[] vals = [5, 3, 8, 1];
var streaming = vals
.Where(v => { Console.WriteLine($" Where {v}"); return v > 2; })
.Select(v => { Console.WriteLine($" Select {v}"); return v * 10; });
foreach (var v in streaming.Take(2))
{
Console.WriteLine($"got {v}");
}
Console.WriteLine("-----------");
var buffering = vals
.Select(v => { Console.WriteLine($" Select {v}"); return v; })
.OrderBy(v => v);
foreach (var v in buffering.Take(2))
{
Console.WriteLine($"got {v}");
}
We trace two chains, each ending with Take(2).
foreach (var v in streaming.Take(2))
The element 5 goes through Where and Select before
the element 3 is read. After two results, Take stops the
enumeration; the elements 8 and 1 are never read.
.OrderBy(v => v);
OrderBy cannot know the smallest element until it has seen all
of them. The first MoveNext call reads the whole source, although
we take only two elements.
$ dotnet run Where 5 Select 5 got 50 Where 3 Select 3 got 30 ----------- Select 5 Select 3 Select 8 Select 1 got 1 got 3
Repeated enumeration
A deferred query is executed again each time it is enumerated. When the query
is expensive, or has side effects, we materialize it once with
ToList or ToArray.
int calls = 0;
var squares = Enumerable.Range(1, 5).Select(n =>
{
calls++;
return n * n;
});
Console.WriteLine(squares.Sum());
Console.WriteLine(squares.Max());
Console.WriteLine(squares.Count());
Console.WriteLine($"selector calls: {calls}");
calls = 0;
int[] cached = squares.ToArray();
Console.WriteLine(cached.Sum());
Console.WriteLine(cached.Max());
Console.WriteLine(cached.Length);
Console.WriteLine($"selector calls: {calls}");
We count how many times the selector is called.
Console.WriteLine(squares.Sum()); Console.WriteLine(squares.Max()); Console.WriteLine(squares.Count());
Each of the three methods enumerates the query, so the five squares are computed three times: fifteen calls.
int[] cached = squares.ToArray();
ToArray runs the query once and stores the results. The later
operations work on the array, and the selector is called only five times.
Code analyzers warn about this problem as possible multiple
enumeration of an IEnumerable (rule CA1851).
$ dotnet run 55 25 5 selector calls: 15 55 25 5 selector calls: 5
Captured variables
A lambda in a query captures variables, not their values. The query uses the values the variables have at the time of enumeration.
List<int> scores = [45, 72, 88, 91, 60, 79];
int threshold = 70;
var passed = scores.Where(s => s >= threshold);
threshold = 85;
Console.WriteLine(string.Join(", ", passed));
var queries = new List<IEnumerable<int>>();
foreach (var limit in new[] { 50, 80 })
{
queries.Add(scores.Where(s => s >= limit));
}
foreach (var q in queries)
{
Console.WriteLine(string.Join(", ", q));
}
We change a variable after creating a query, and create queries in a loop.
int threshold = 70; var passed = scores.Where(s => s >= threshold); threshold = 85;
The query was created with the threshold 70, but it runs with 85. Only the scores 88 and 91 pass.
foreach (var limit in new[] { 50, 80 })
{
queries.Add(scores.Where(s => s >= limit));
}
A foreach loop creates a new limit variable in each
iteration, so each query keeps its own limit. With a for loop
counter, all queries would share one variable.
$ dotnet run 88, 91 72, 88, 91, 60, 79 88, 91
Deferred exceptions
Since the query code runs during enumeration, exceptions thrown by lambdas appear there too, not where the query is created. Argument validation of the LINQ operators, however, is done immediately.
int[] vals = [10, 5, 0, 2];
var ratios = vals.Select(v => 100 / v);
Console.WriteLine("query created");
try
{
foreach (var r in ratios)
{
Console.WriteLine(r);
}
}
catch (DivideByZeroException e)
{
Console.WriteLine($"during enumeration: {e.Message}");
}
try
{
Func<int, bool>? predicate = null;
var q = vals.Where(predicate!);
}
catch (ArgumentNullException e)
{
Console.WriteLine($"at creation: {e.ParamName}");
}
We divide by the elements of an array that contains a zero.
var ratios = vals.Select(v => 100 / v);
Creating the query succeeds. The division by zero happens on the third element, after two results have been printed.
var q = vals.Where(predicate!);
A null predicate is rejected at once with an
ArgumentNullException, before any enumeration.
$ dotnet run query created 10 20 during enumeration: Attempted to divide by zero. at creation: predicate
Writing deferred methods
Iterator methods, which use yield return, are deferred as well:
their body starts running on the first MoveNext call. This also
delays argument checks. LINQ operators avoid this by validating arguments in
a regular method that returns an inner iterator.
var evens = Evens(10);
Console.WriteLine("iterator created");
foreach (var e in evens.Take(3))
{
Console.WriteLine(e);
}
try
{
var bad = Evens(-1);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"error: {e.ParamName} = {e.ActualValue}");
}
IEnumerable<int> Evens(int max)
{
ArgumentOutOfRangeException.ThrowIfNegative(max);
return Iterate();
IEnumerable<int> Iterate()
{
for (int i = 0; i <= max; i += 2)
{
Console.WriteLine($" yielding {i}");
yield return i;
}
}
}
We write a method that yields even numbers up to a limit.
ArgumentOutOfRangeException.ThrowIfNegative(max); return Iterate();
Evens is a normal method, so the check runs as soon as it is
called. It returns the iterator implemented by the local function.
foreach (var e in evens.Take(3))
The iterator yields its values on demand; after three numbers,
Take stops it. Had the check been inside the iterator,
Evens(-1) would not throw until enumerated.
$ dotnet run iterator created yielding 0 0 yielding 2 2 yielding 4 4 error: max = -1
Deferred execution in database queries
With Entity Framework Core, a query over a DbSet is an
IQueryable<T>. Its operators build an expression tree,
which is translated to SQL and sent to the database only when the query is
enumerated. This allows us to compose a query in several steps and still run
a single SQL statement.
The example needs the Microsoft.EntityFrameworkCore.Sqlite
package (we used version 10.0.15); it creates a SQLite database file and logs
the executed SQL commands.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using var db = new ShopContext();
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.Products.AddRange(
new Product { Name = "Laptop", Category = "computers", Price = 999 },
new Product { Name = "Mouse", Category = "accessories", Price = 25 },
new Product { Name = "Monitor", Category = "computers", Price = 249 },
new Product { Name = "Keyboard", Category = "accessories", Price = 120 });
db.SaveChanges();
db.Logging = true;
Console.WriteLine("building query");
string? category = "accessories";
IQueryable<Product> query = db.Products
.Where(p => p.Price > 100)
.OrderBy(p => p.Name);
if (category is not null)
{
query = query.Where(p => p.Category == category);
}
Console.WriteLine("query built, calling ToList");
var results = query.ToList();
db.Logging = false;
foreach (var p in results)
{
Console.WriteLine($"{p.Name} {p.Price}");
}
class Product
{
public int Id { get; set; }
public required string Name { get; set; }
public required string Category { get; set; }
public int Price { get; set; }
}
class ShopContext : DbContext
{
public bool Logging { get; set; }
public DbSet<Product> Products => Set<Product>();
protected override void OnConfiguring(DbContextOptionsBuilder options) =>
options.UseSqlite("Data Source=shop.db")
.LogTo(msg => { if (Logging) Console.WriteLine(msg); },
[DbLoggerCategory.Database.Command.Name], LogLevel.Information,
Microsoft.EntityFrameworkCore.Diagnostics.DbContextLoggerOptions.None);
}
We build a query of products in two steps and then materialize it.
IQueryable<Product> query = db.Products
.Where(p => p.Price > 100)
.OrderBy(p => p.Name);
These calls only extend the expression tree; nothing is sent to the database.
if (category is not null)
{
query = query.Where(p => p.Category == category);
}
An additional condition is added depending on a runtime value. The query is still not executed.
var results = query.ToList();
ToList runs the query. The log shows that one SQL statement
combines both Where conditions and the ordering. The captured
category variable becomes the @category parameter.
$ dotnet run building query query built, calling ToList Executed DbCommand (0ms) [Parameters=[@category='?' (Size = 11)], CommandType='Text', CommandTimeout='30'] SELECT "p"."Id", "p"."Category", "p"."Name", "p"."Price" FROM "Products" AS "p" WHERE "p"."Price" > 100 AND "p"."Category" = @category ORDER BY "p"."Name" Keyboard 120
Source
Deferred execution and lazy evaluation
Classification of standard query operators by manner of execution
In this article we have explained LINQ deferred execution in C#. See also the LINQ, LINQ Where, and yield tutorials.
Author
List all C# tutorials.