Module 1 · Foundations · Lesson 2 of 24
Deferred Execution and Multiple Enumeration: Paying for the Same Query Twice
Deferred execution delays LINQ work until results are consumed. Avoid paying for multiple enumeration by saving bounded results or computing several answers in one pass.
This lesson focuses on LINQ to Objects: queries that use Enumerable methods to process .NET sequences, rather than translate a query for a database. You will learn to count the work each consumer requests, decide when to keep results, and recognize when another pass might produce different answers.
What is deferred execution in LINQ?
A deferred query describes work to do later. Declaring the query does not run its filtering or transformation over the source. Enumeration means requesting elements from a sequence, usually through foreach or a LINQ method that consumes results.
Standard Where and Select queries are deferred. Where tests source elements against a condition. Select computes an output for each element it processes. Neither operator automatically caches its results for later reuse.
Guess what the counter shows before and after the loop:
int transformations = 0;
var source = new[] { 1, 2, 3 };
var query = source.Select(number =>
{
transformations++;
return number * 10;
});
Console.WriteLine($"After declaration: {transformations}");
foreach (int number in query)
{
Console.WriteLine(number);
}
Console.WriteLine($"After enumeration: {transformations}");After declaration: 0 10 20 30 After enumeration: 3
The declaration creates a query that remembers the source and transformation.
The loop requests results. Each request causes the transformation to run for another source element.
Immediate execution means a call computes its answer or stores its results now, rather than returning work to execute later. Typical immediate operators include Count, Any, First, Single, Sum, Max, ToList, ToArray and ToDictionary. Operators returning IEnumerable<T> are usually deferred.
flowchart TD
Q["Declare a Where or Select query"] -->|creates| D["Description of work"]
D -->|consumer requests| E["Query execution"]
E -->|produces| R["Results for that consumer"]
The consumer starts the query's work; merely holding the query does not store its results.
The mistake to avoid. A variable holding a deferred query is not a variable holding already-computed results. Another enumeration can run the transformation again.
In an interview, say: “Deferred execution delays work until results are consumed. Operators returning IEnumerable<T> are usually deferred. Immediate operators such as Count, First, Sum, ToList and ToArray execute when called. Standard Where and Select queries do not cache results, so another enumeration can repeat the work.”
Microsoft's standard query operators overview explains how an enumerable query captures its arguments and uses them when enumerated.
Does Any followed by Count enumerate a query twice?
They are separate consumption points, but that does not necessarily mean two complete scans.
Multiple enumeration means consuming the same IEnumerable<T> more than once. Each consumer makes its own request. A later consumer does not continue where an earlier consumer stopped.
For a filtered sequence, Any() can stop at the first match. See the Enumerable.Any reference for its early-stopping behavior. Its worst-case traversal is O(n), because there might be no match. Count() must establish the full number of matches.
A predicate is the condition used to decide whether an element matches. Predict the predicate-call count for each consumer:
var source = new[] { 1, 2, 3, 4, 5, 6 };
int predicateCalls = 0;
var matches = source.Where(number =>
{
predicateCalls++;
return number % 2 == 0;
});
Console.WriteLine($"After declaration: {predicateCalls}");
predicateCalls = 0;
bool any = matches.Any();
Console.WriteLine($"Any: {any}; predicate calls: {predicateCalls}");
predicateCalls = 0;
int count = matches.Count();
Console.WriteLine($"Count: {count}; predicate calls: {predicateCalls}");
predicateCalls = 0;
foreach (int number in matches)
{
Console.WriteLine($"Match: {number}");
}
Console.WriteLine($"Display predicate calls: {predicateCalls}");After declaration: 0 Any: True; predicate calls: 2 Count: 3; predicate calls: 6 Match: 2 Match: 4 Match: 6 Display predicate calls: 6
Any() tests 1 and then 2. It finds a match and stops after 2 calls.
Count() starts a fresh pass. It tests all six numbers and reports three matches: 6 calls.
The loop starts another fresh pass. It displays 2, 4 and 6, but must inspect every source element to find them: 6 calls.
The total is 14 predicate calls, not 18. This counter demonstrates repeated work; it is not a timing benchmark.
Exact work also depends on the source. A collection may already expose its count, allowing an operation to avoid a traversal. See Any and Count fast paths for those differences.
The mistake to avoid. Do not count LINQ calls and assume each means a full scan. Count source visits separately for each consumer, including early stopping and available optimizations.
In an interview, say: “Any and Count are separate consumption points. On a filtered sequence, Any can stop at the first match, while Count must establish the full count. Multiple enumeration can repeat filtering, computation, I/O or side effects, but it is not always two full scans.”
Is deferred execution the same as streaming?
No. Deferred execution describes when work starts. Streaming describes producing results incrementally, without first collecting the whole source.
Where can stream: it examines elements until it finds the next match.
Buffering means retaining elements temporarily before returning results. Enumerating ordered output from OrderBy normally requires buffering the source first.
Compare when the first result reaches each loop:
var source = new[] { 3, 1, 2 };
var traced = source.Select(number =>
{
Console.WriteLine($"Read: {number}");
return number;
});
Console.WriteLine("Where:");
foreach (int number in traced.Where(number => number > 1))
{
Console.WriteLine($"First result: {number}");
break;
}
Console.WriteLine("OrderBy:");
foreach (int number in traced.OrderBy(number => number))
{
Console.WriteLine($"First result: {number}");
break;
}Where: Read: 3 First result: 3 OrderBy: Read: 3 Read: 1 Read: 2 First result: 1
The Where loop reads 3 and immediately returns it. Breaking the loop prevents further source reads.
The OrderBy loop reads 3, 1 and 2 before returning its first result, 1. Breaking after that result does not undo the source work already performed.
Both queries are deferred. Only one streams results in this example. Microsoft's classification of standard query operators by manner of execution identifies streaming and non-streaming operators. Its LINQ to XML article Deferred execution and lazy evaluation explains lazy and eager evaluation.
The mistake to avoid. Do not promise low memory use or little source work just because a query is deferred. An operator may wait until enumeration and then buffer the whole source.
In an interview, say: “Deferred and streaming are different. Deferred means execution starts later. Streaming means results can arrive incrementally. Where can stream, while enumerating ordered output from OrderBy normally requires buffering the source before returning the first result.”
How can you avoid multiple enumeration of an expensive query?
There are three useful choices:
- Repeat enumeration when it is cheap, repeatable, and reading current source data is intended.
- Keep bounded results when several consumers need those same results.
- Compute several summaries during one pass when you do not need to keep individual results.
Materialization means executing a query and storing the results, commonly with ToList() or ToArray(). Microsoft's LINQ introduction explains this under Immediate.
Materialization still pays the original query's execution cost. It moves later consumers to the stored collection; it does not make their work disappear.
This program compares storing matches with computing two summaries directly:
var source = new[] { 1, 2, 3, 4, 5, 6 };
int predicateCalls = 0;
var query = source.Where(number =>
{
predicateCalls++;
return number % 2 == 0;
});
var saved = query.ToList();
Console.WriteLine($"Materialization predicate calls: {predicateCalls}");
Console.WriteLine($"Saved count: {saved.Count}");
Console.WriteLine($"Saved any: {saved.Count != 0}");
foreach (int number in saved)
{
Console.WriteLine($"Saved match: {number}");
}
Console.WriteLine($"Predicate calls after display: {predicateCalls}");
int count = 0;
long total = 0;
int visits = 0;
foreach (int number in source)
{
visits++;
if (number % 2 == 0)
{
count++;
total += number;
}
}
Console.WriteLine($"Single pass: visits={visits}; count={count}; total={total}");Materialization predicate calls: 6 Saved count: 3 Saved any: True Saved match: 2 Saved match: 4 Saved match: 6 Predicate calls after display: 6 Single pass: visits=6; count=3; total=12
ToList() tests all six inputs and saves three matches. Reading the list's Count property takes O(1) time, as documented in the List<T>.Count reference. Displaying its contents still takes O(r) time, where r is the number of matches, but does not rerun the original predicate.
For a linear filter over n inputs, creating the list takes O(n) time and retains O(r) results. Each later complete list traversal costs O(r).
The final loop computes the count and total with six visits and O(1) extra space. It does not retain matching elements. This is useful when you only need summaries, rather than a reusable collection.
The mistake to avoid. Do not add ToList() automatically to every query. It trades repeated computation for memory and immediate work, even if a later consumer would have stopped early.
In an interview, say: “For expensive results that must be reused, I materialize a bounded query once with ToList or ToArray. That retains O(r) results, and later traversals still cost time. If I only need several summaries, I compute them in one pass without storing every result.”
Will a deferred LINQ query see source changes?
A deferred query reads source state when enumerated. Changes made before a later pass can therefore change its results.
ToList() saves which elements that pass produced. For class instances, it saves references to the same objects. For structs, it saves copies of their values. It is not a deep copy, which would also create independent copies of the referenced objects.
Predict which names appear in the live query and saved list:
var source = new List<WorkItem> { new WorkItem("A") };
var query = source.Where(item => item.Name.Length > 0);
Console.WriteLine("Initially: " + string.Join(", ", query.Select(item => item.Name)));
source.Add(new WorkItem("B"));
Console.WriteLine("Before saving: " + string.Join(", ", query.Select(item => item.Name)));
var saved = query.ToList();
source.Add(new WorkItem("C"));
source[0].Name = "A changed";
Console.WriteLine("Live query: " + string.Join(", ", query.Select(item => item.Name)));
Console.WriteLine("Saved list: " + string.Join(", ", saved.Select(item => item.Name)));
public sealed class WorkItem(string name)
{
public string Name { get; set; } = name;
}Initially: A Before saving: A, B Live query: A changed, B, C Saved list: A changed, B
The first pass sees A. Adding B before the next pass makes that pass see A and B. ToList() then saves references to those two objects.
Adding C afterward changes only the source collection's membership. The live query sees C; the saved list does not contain it.
Changing A's name is different. Both collections refer to that same object, so both display A changed.
Repeated work can also repeat a side effect: an action beyond producing a return value, such as writing a log or changing a counter. The predicate counters earlier deliberately used side effects to expose execution. Real query code should not rely on those actions happening only once.
The mistake to avoid. A saved list fixes which results that pass produced, not the future state of every referenced object. It also does not update automatically when the source gains elements.
In an interview, say: “A deferred query reads the source when enumerated, so changes before another pass can affect the results. ToList saves the elements produced by one pass. For class instances, it keeps references to the same objects rather than copying those objects.”
Can any IEnumerable be safely enumerated again?
No. IEnumerable<T> provides enumeration. In the example below, a second pass reruns the method and sees an element added after the first pass.
An in-memory list and a sequence that reads external data can have the same declared interface but very different costs. Another pass might repeat I/O, observe changed data, or fail because a required resource has already been closed. Check what the source documents about being read more than once, and whether the file, connection or reader behind it is still open.
An iterator method uses yield return to produce elements as the consumer requests them. Calling it returns a sequence without running its body yet. Each foreach over that sequence starts the body again; stopping early can leave part of the body unexecuted.
Here, each complete pass prints Reading source and reads the current list:
var source = new List<int> { 1, 2 };
var query = ReadNumbers(source);
Console.WriteLine("First pass:");
foreach (int number in query)
{
Console.WriteLine(number);
}
source.Add(3);
Console.WriteLine("Second pass:");
foreach (int number in query)
{
Console.WriteLine(number);
}
static IEnumerable<int> ReadNumbers(List<int> source)
{
Console.WriteLine("Reading source");
foreach (int number in source)
{
yield return number;
}
}First pass: Reading source 1 2 Second pass: Reading source 1 2 3
Both passes print Reading source, showing that the iterator body runs again. If the body read a file instead, another pass could repeat that file read.
The .NET analyzer rule CA1851: Possible multiple enumerations of IEnumerable collection helps locate possible repeated consumption. An analyzer checks code for patterns that may cause problems; it does not measure execution. CA1851 is off by default. Turn it on by adding dotnet_diagnostic.CA1851.severity = warning under the applicable C# file section in .editorconfig.
Use the warning as a reason to inspect the source and consumers. A known list may make a count cheap. An expensive generated sequence may justify materialization or a single-pass redesign.
The mistake to avoid. Do not assume an IEnumerable<T> parameter can be consumed repeatedly merely because foreach is available. That interface alone does not establish the source's behavior.
In an interview, say: “No, IEnumerable<T> does not guarantee repeatable enumeration. A source may repeat external work, return different data, or fail on another pass. I check whether the source supports another read and whether any file, connection or reader it needs is still open. I enable CA1851 to help find repeated consumption.”
Check yourself
A deferred Where query filters 100 source elements with a constant-time predicate. Its first match is the fourth element. You call Any(), then Count(), then display every match with foreach. How many predicate calls occur for these three consumers?
Show answer
Correct answer: A
Any stops after four tests. Count and the complete foreach each test all 100 source elements. The total is 4 + 100 + 100 = 204.
You call ToList() on a query returning mutable class instances. You then add another object to the original source and change a property on an object already in the saved list. What should you expect?
Show answer
Correct answer: D
ToList saves the results of one pass. It does not track later source additions or deep-copy referenced objects.
Going deeper
Consumer choice can change the work. The ordered foreach example demonstrates buffering when enumerating ordered output. Do not extend that trace to every method called on an ordered query. A consumer can use an optimized route instead of requesting the full ordered sequence. Continue with OrderBy buffering and complexity for those details.
Counters have limits. Predicate-call counts show calls made in these programs. They do not measure sorting comparisons, memory allocation, or elapsed time. Some operators can also avoid transformations whose outputs are unnecessary for a particular consumer. Keep business actions outside query transformations when they must happen a specific number of times.
Materialization needs a practical bound. A query that produces too many results may exhaust available memory. A sequence that never ends cannot finish materializing. Decide how much data you can retain before choosing ToList() as a fix.
CA1851 needs to understand helper methods. Its documentation describes configuration for custom methods that consume sequences and custom methods that extend a deferred query. By default, custom methods accepting IEnumerable arguments are assumed not to enumerate them. Configure those helpers when needed; absence of a warning is not proof that a query is consumed only once.
Sources
- CA1851: Possible multiple enumerations of 'IEnumerable' collection - .NET | Microsoft Learn: Repeated enumeration costs and side effects, materialization trade-offs, collection-specific optimizations, and analyzer configuration for custom consuming and chain methods.
- Deferred execution and lazy evaluation - LINQ to XML - .NET | Microsoft Learn: Deferred execution versus incremental processing, and OrderBy processing the source before returning ordered output.
- Standard query operators overview - C# | Microsoft Learn: Enumerable queries capturing arguments and executing operator logic during enumeration; immediate scalar consumers versus deferred query construction.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 28 Nov 2026 ·