Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 16

    Module 1 · LINQ to Objects · Lesson 1 of 16

    Deferred Execution and Repeated Enumeration in LINQ to Objects

    Save a filter now, read the study log later

    Imagine the study planner has a list of today's session lengths. You want to show the sessions that lasted at least 20 minutes. Someone logs another session before you open the report. Whether it appears depends on when the report reads the list.

    LINQ gives C# ways to work with a sequence of items. Where describes a filter, a rule that keeps only matching items. The expression minutes => minutes >= 20 takes one number and answers whether to keep it. Defining this query stores that rule for this source without walking the list. Enumerating means asking for its results one at a time, as foreach does. This delay until you ask for results is deferred execution.

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    var studyLog = new List<int> { 10, 20 };
    var report = studyLog.Where(minutes => minutes >= 20);
    
    studyLog.Add(30);
    foreach (int minutes in report)
        Console.WriteLine(minutes);

    It prints 20, then 30. The query did not save the matching numbers at definition. The loop reads the list after the addition. If you loop over this same query again, it reads the source again; it does not reuse a saved result.

    If the report needs the matches as they were at a particular moment, call ToArray() at that moment. It reads the query immediately and stores the resulting integers in a separate array. This is called materializing the query.

    Add .ToArray() after the Where call, before Add(30). Leave the loop as it is. What prints?

    A 20 only
    B 20, then 30
    C 10, then 20
    D Nothing, because the query already ran once
    Show answer

    Correct answer: A

    ToArray reads the filter before the addition and saves only 20. The loop reads the saved array, not the later list.

    Option B: The later 30 was never put in the saved array.

    Option C: Ten does not meet the minimum.

    Option D: An array can be read after it is created.

    Next, follow the original walkthrough to see how often a filter runs when read twice. Its logging is a teaching aid, not a recommendation to put logging or mutations in a filter.

    Microsoft Learn: LINQ execution and saved results

    Lesson video

    Run and inspect the complete example

    Use a separate console project with the .NET 10 SDK and implicit usings enabled. Keep this listing together as Program.cs; the later fragments are reading aids, not separate complete programs. Predict the values before reading the transcript in the walkthrough.

    Deferred execution and repeated enumeration in LINQ to Objects

    Program.cs

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    var source = new[] { 1, 2, 3, 4 };
    int predicateCalls = 0;
    
    IEnumerable<int> query = source.Where(n =>
    {
        predicateCalls++;
        Console.WriteLine($"Filtering {n}");
        return n % 2 == 0;
    });
    
    Console.WriteLine("Query defined, but not yet executed.");
    Console.WriteLine($"Predicate calls so far: {predicateCalls}");
    
    Console.WriteLine("First enumeration:");
    foreach (var item in query)
    {
        Console.WriteLine($"Result {item}");
    }
    
    Console.WriteLine($"Predicate calls after first enumeration: {predicateCalls}");
    
    Console.WriteLine("Second enumeration:");
    foreach (var item in query)
    {
        Console.WriteLine($"Result {item}");
    }
    
    Console.WriteLine($"Predicate calls after second enumeration: {predicateCalls}");
    
    Console.WriteLine("Materialize once with ToList:");
    predicateCalls = 0;
    var snapshot = query.ToList();
    Console.WriteLine($"Predicate calls while materializing: {predicateCalls}");
    
    Console.WriteLine("Enumerate snapshot twice:");
    foreach (var item in snapshot)
    {
        Console.WriteLine($"Snapshot item {item}");
    }
    foreach (var item in snapshot)
    {
        Console.WriteLine($"Snapshot item again {item}");
    }

    Enumeration runs the deferred pipeline

    In LINQ to Objects, operators like Where, Select, Skip, and Take typically create an iterator pipeline. The pipeline is lazy: it pulls elements from the source only as needed during enumeration.

    The important consequence is that enumeration is repeatable work. If the source is an in-memory collection and you loop over the query twice, the query logic runs twice.

    This is different from some database providers such as Entity Framework Core. There, the query is usually an expression tree first. The provider may translate it to SQL, send it to the database, and materialize results from the database result set. Re-enumerating the query may cause a new database round-trip, not just a re-run of in-memory operators. The exact translation behavior depends on the provider, but the core interview distinction is:

    • LINQ to Objects: deferred execution means iterator logic runs when you enumerate.
    • Database provider: the provider may translate the query into another language, then execute remotely.

    For interviews, be precise: deferred execution does not mean “the result is always recalculated from scratch in every scenario.” It means the work is postponed until enumeration. If you materialize once, you create a stable snapshot in memory.

    Failure modes

    Common mistakes include:

    • Assuming query definition equals query execution: Constructing a deferred Where pipeline does not enumerate its source; this does not make every LINQ operator or argument expression deferred.
    • Enumerating twice unintentionally: For example, calling Count() and then iterating again may traverse the source twice.
    • Putting side effects inside query operators: Logging, counters, or mutations may happen more than expected.
    • Assuming IEnumerable<T> means cheap reuse: Reuse can still repeat expensive iteration.
    • Confusing LINQ to Objects with database LINQ: Database providers can translate and execute remotely, so the performance model is different.

    Interview edge cases: demand, state and lifetime

    The practice examples use LINQ to Objects and modern C# (C# 9 or later for top-level programs), with the usual System, System.Collections.Generic and System.Linq imports. Unless a question says otherwise, inputs are non-null and are not modified concurrently.

    • A consumer controls how much of a streaming pipeline runs. First can stop after the first matching result; a full foreach can visit the whole input. A selector that parses invalid text can therefore fail during later consumption even when obtaining the first result succeeded.
    • A lambda can read a captured variable when it executes. Changing a threshold after query construction can change the result. If a fixed rule is required, make the intended value and evaluation boundary explicit.
    • AsEnumerable creates no result snapshot. It exposes an enumerable view; adding to a list before enumeration can still change the values observed. IEnumerable alone also promises neither cheap nor identical repeated traversal.
    • Deferred and streaming are different properties. OrderBy is constructed without enumerating its input, but ordered enumeration must account for the full input before yielding its first sorted result.
    • Deferred work must fit the lifetime of its data source. Returning a query that depends on a reader disposed by the returning method is unsafe. Consume bounded results while the reader is open, or design an iterator that owns the reader until enumeration finishes.
    • Keep argument validation separate from work inside a delegate. A null source can be rejected at query construction, while a failure inside a deferred predicate or selector occurs only if that delegate runs. Debugger result expansion may itself enumerate a query.

    Trace one extra consumer

    Before changing the program, write the predicate count at definition, after the first full loop, after the second loop and after the reset followed by ToList(). Then consider adding one full traversal of query between the first two loops. How many additional predicate calls would it cause?

    Hint: this source has four elements; every full traversal runs the predicate once for each.

    Check the trace

    The original checkpoints are 0, 4, 8 and 4 after the reset/materialization. The extra full traversal adds four calls. Traversing the stored snapshot does not call this predicate again. A short-circuiting consumer may do less work, so name the consumer in the explanation.

    Deferred execution in one table

    Building this Where query
    Does not run its predicate yet source.Where(...) makes 0 predicate calls
    Enumerating
    Runs the pipeline First foreach: 4 predicate calls
    Enumerating again
    Runs it again Second foreach: 8 calls in total
    ToList()
    Runs once and stores a snapshot Looping over the snapshot calls no predicate

    A Where query over 4 items is enumerated twice with foreach. How many times does the predicate run in total?

    A 4
    B 8
    C 0, because the result is cached
    D 2
    Show answer

    Correct answer: B

    Each enumeration replays the pipeline, so the predicate runs 4 times per foreach. This Where query does not cache results; ToList() or ToArray() can materialize them for reuse.

    Code walkthrough

    The code starts by defining a source array and a counter. The counter is important because it proves how many times the predicate runs.

    The query uses Where, but nothing happens yet. That is deferred execution.

    When the first foreach runs, the source is traversed and the predicate runs once per source element. The matching values are yielded as the loop asks for them.

    When the second foreach runs, the same pipeline is executed again. The query is the same variable, but it is not a stored result set. It is a reusable recipe.

    The ToList() call changes the shape of the program. It forces enumeration immediately, stores the matching values, and lets you loop over the stored list repeatedly without rerunning the predicate.

    That is the key interview answer: deferred execution delays work; repeated enumeration repeats work; materialization creates a stable snapshot.

    Output

    Text
    Query defined, but not yet executed.
    Predicate calls so far: 0
    First enumeration:
    Filtering 1
    Filtering 2
    Result 2
    Filtering 3
    Filtering 4
    Result 4
    Predicate calls after first enumeration: 4
    Second enumeration:
    Filtering 1
    Filtering 2
    Result 2
    Filtering 3
    Filtering 4
    Result 4
    Predicate calls after second enumeration: 8
    Materialize once with ToList:
    Filtering 1
    Filtering 2
    Filtering 3
    Filtering 4
    Predicate calls while materializing: 4
    Enumerate snapshot twice:
    Snapshot item 2
    Snapshot item 4
    Snapshot item again 2
    Snapshot item again 4

    Snapshot scope

    Materialization stores the selected entries, not deep copies of referenced objects. A later change to a shared mutable object can still be visible in both collections.

    Optional video

    Microsoft .NET · 4:47. Query composition, execution and repeated enumeration. Watching is optional.

    Watch on YouTube.

    Quick reference

    Deferred execution at a glance

    • Query construction describes work; enumeration performs the deferred work. Argument validation can still happen immediately.
    • Where and Select can stream results. A consumer such as First may stop early.
    • A full second traversal can repeat source reads, predicates and projections.
    • Captured variables are read when the delegate runs; they are not automatic value snapshots.
    • AsEnumerable() does not copy or cache results.
    • ToList() and ToArray() store a result for deliberate reuse.
    • Deferred does not mean streaming: sorting and grouping can buffer input.
    • Keep resource lifetime and provider boundaries explicit. Database-backed LINQ needs its own translation and execution checks.

    Practice

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·