Skip to content

2.6 — Deferred vs Immediate Execution

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.5 LINQ basics · Next: 2.7 Expression trees

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • A LINQ query is a recipe, not a meal. Writing it does nothing. It only runs when something asks for results.
  • Enumerating it twice runs it twice — two database round trips, two file reads, two of everything.
  • The fix is .ToList() once, at the point you know you need the data.

The concept

This is the single most surprising thing about LINQ, and it causes real production bugs.

When you write this:

var expensive = orders.Where(o => o.Total > 1000);

nothing has happened. No filtering. No looping. expensive is not a list of orders — it is an object that knows how to produce those orders when asked.

The cooking analogy fits well. A recipe card that says "chop onions, fry them, add stock" is not soup. You can carry the card around, hand it to someone, even add steps to it. No cooking happens until someone actually stands at the stove.

And here is the consequence people miss: hand the same recipe to two people and the meal gets cooked twice. LINQ does exactly that. Every time you enumerate a query, the whole thing runs again from the start.


How it works

Proving it to yourself

var numbers = new List<int> { 1, 2, 3 };

var query = numbers.Where(n =>
{
    Console.WriteLine($"  testing {n}");
    return n > 1;
});

Console.WriteLine("query created");
Console.WriteLine("--- first loop ---");
foreach (var n in query) { }
Console.WriteLine("--- second loop ---");
foreach (var n in query) { }

Output:

query created            ← nothing tested yet
--- first loop ---
  testing 1
  testing 2
  testing 3
--- second loop ---
  testing 1              ← it all runs AGAIN
  testing 2
  testing 3

The filter ran six times for three items.

The other half: the source can change underneath you

Because the query holds a reference to the source rather than a copy, changing the source changes the results:

var numbers = new List<int> { 1, 2, 3 };
var evens = numbers.Where(n => n % 2 == 0);

Console.WriteLine(evens.Count());     // 1  (just the 2)

numbers.Add(4);
numbers.Add(6);

Console.WriteLine(evens.Count());     // 3  — the query saw the new items!

The evens variable was never reassigned, yet its answer changed. That is deferred execution. Sometimes it is exactly what you want; more often it is a bug waiting to happen.

What triggers execution

Deferred — builds the recipe Immediate — cooks it
Where, Select, SelectMany ToList, ToArray, ToDictionary, ToHashSet
OrderBy, ThenBy, Take, Skip Count, Sum, Average, Min, Max
Distinct, Concat, Union, Reverse First, Single, Last, ElementAt
GroupBy*, Join* Any, All, Contains
foreach over it

* GroupBy and Join are technically deferred, but when they do run they have to read the entire source before yielding anything, because they cannot know the groups until they have seen everything.


⚠️ The bugs this causes

1. The same database query running several times

// BAD — three separate SQL queries
var orders = _db.Orders.Where(o => o.CustomerId == id);

var count = orders.Count();                     // SQL round trip 1
var total = orders.Sum(o => o.Total);           // SQL round trip 2
var list  = orders.ToList();                    // SQL round trip 3

Three trips to the database for data you only needed once. On a busy endpoint that is three times the database load.

// GOOD — one query, then work in memory
var orders = await _db.Orders
    .Where(o => o.CustomerId == id)
    .ToListAsync(ct);                           // SQL round trip 1, and only

var count = orders.Count;                       // now a plain property
var total = orders.Sum(o => o.Total);           // now in-memory

2. Enumerating after the DbContext is gone

public IEnumerable<Order> GetOrders(Guid id)
{
    using var db = new AppDbContext();
    return db.Orders.Where(o => o.CustomerId == id);
}       // ← the DbContext is disposed HERE, before anything ran

var orders = GetOrders(id);
foreach (var o in orders) { }
// ObjectDisposedException — "Cannot access a disposed context instance"

The query never ran inside the method. By the time it does, its database connection is gone. Add .ToList() before returning.

3. The captured-variable surprise

var threshold = 100;
var expensive = orders.Where(o => o.Total > threshold);

threshold = 1000;                      // change the variable

var results = expensive.ToList();      // uses 1000, NOT 100

The lambda captured the variable, not its value at the time (1.13). Because execution is deferred, it reads whatever the variable holds at execution time.

4. Exceptions thrown far from their cause

var parsed = lines.Select(l => int.Parse(l));   // no exception yet

// ... 40 lines of unrelated code ...

var sum = parsed.Sum();      // FormatException thrown HERE

The stack trace points at Sum(), which has nothing to do with the malformed input.


Code

The practical rule, applied:

public async Task<OrderReport> BuildReportAsync(Guid customerId, CancellationToken ct)
{
    // Build the query — still just a recipe. Nothing has run.
    var query = _db.Orders
        .Where(o => o.CustomerId == customerId)
        .Where(o => o.Status == OrderStatus.Complete);

    // Compose conditionally — still free, still nothing running
    if (_settings.ExcludeRefunds)
        query = query.Where(o => !o.WasRefunded);

    // Execute ONCE, deliberately, while the context is alive
    var orders = await query
        .Select(o => new OrderSummary(o.Id, o.Total, o.CreatedAt))
        .ToListAsync(ct);

    // Everything below works on the in-memory list. No more SQL.
    return new OrderReport
    {
        Count      = orders.Count,
        Total      = orders.Sum(o => o.Total),
        Largest    = orders.MaxBy(o => o.Total),
        FirstOrder = orders.MinBy(o => o.CreatedAt)
    };
}

The pattern to remember:

  1. Compose while it is cheap. Adding Where clauses to an unexecuted query costs nothing and lets you build conditional filters cleanly.
  2. Execute once, on purpose, at the moment you need real data.
  3. After that, you have a list — use it as many times as you like.

When deferred execution is a feature

It is not always a hazard. Conditional query building, as above, only works because execution is deferred. So does infinite generation:

static IEnumerable<int> Naturals()
{
    var i = 0;
    while (true) yield return i++;      // never ends
}

var firstTen = Naturals().Take(10).ToList();    // fine — Take stops it

That would be impossible if Naturals() had to finish before Take could run.


Interview questions

Q: What is deferred execution in LINQ?

Most LINQ operators do not run when you write them. They return an object that describes the query, and the work only happens when something enumerates it — a foreach, or an operator like ToList, Count or First. So a LINQ statement is a recipe rather than a result. The practical consequence is that enumerating the same query variable twice executes it twice, and that the source data is read at execution time, not at the point the query was written.

Q: What problems does it cause in practice?

Three main ones. Multiple enumeration — calling Count() and then ToList() on the same query means two full executions, which against a database is two round trips. Disposed context — if a method builds a query over a DbContext and returns it without calling ToList, the context is disposed before the query runs and enumeration throws. And late exceptions — a parsing error inside a Select surfaces wherever the query is finally enumerated, so the stack trace points somewhere unrelated to the actual problem.

Q: How do you avoid multiple enumeration?

Call ToList() or ToArray() once, at the point you know you need the data, and use the resulting collection from then on. The signal to watch for is a variable of type IEnumerable<T> being used more than once — most analysers, including ReSharper, flag it as "possible multiple enumeration". The other half is being deliberate about method signatures: returning IEnumerable<T> from a data access method invites the problem, so I return IReadOnlyList<T> after materialising inside.

Q: Is deferred execution ever useful?

Yes, and it is why the design exists. It lets you build a query in pieces — adding Where clauses conditionally based on which filters a user supplied — and only pay for it once, as a single SQL statement. It also allows infinite sequences, because Take(10) can stop an endless generator after ten items. And it means an early-exit operator like First stops the whole pipeline as soon as it has an answer instead of processing everything.


Traps ⚠️

  • Enumerating a query variable twice executes it twice. Two database round trips, two file reads, two of whatever the source is.
  • Returning an unexecuted query from a method whose DbContext is disposed throws ObjectDisposedException at the caller.
  • Captured variables are read at execution time, not when the query was written.
  • Exceptions surface at the enumeration point, not where the faulty operation was declared.
  • OrderBy and GroupBy buffer the entire source before producing anything, so they are deferred but not streaming.
  • .ToList() in the middle of a chain throws away laziness for everything after it, and materialises more rows than you need.
  • A query over a mutable collection sees later changes. The result can differ between two enumerations even with no code change in between.


Sources