الانتقال إلى المحتوى
.NETC#· 7 دقائق للقراءة

Your IEnumerable Holds No Data: LINQ Deferred Execution and Multiple Enumeration

A LINQ query is a recipe, not a result. Every enumeration cooks it again, with fresh data and fresh side effects.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

An export job logs "Exporting 1,204 orders," then writes 1,207 rows to the CSV file. The database log shows the same SELECT twice for every run. Nobody got the math wrong: the export method received an IEnumerable<Order>, called Count() for the log line, then looped over it to write the file. Each of those ran the query, and three new orders arrived in between.

The common misconception

The belief: var pending = orders.Where(o => o.IsPending); filters the orders and stores the result in pending. Reading pending twice should cost nothing extra and give the same answer both times.

It's an easy belief to hold. The variable looks and behaves like a collection: its type name sounds like one, you can foreach over it, call Count() on it and pass it around, and the debugger even lists its items when you expand it, quietly running the query to do so. Most of the time the source is a small in-memory list that doesn't change, so a second pass gives the same answer in microseconds and nothing looks wrong.

What actually happens

A query is a recipe, not a result

Operators such as Where, Select and OrderBy don't touch the data. They return an object that remembers the source and the steps. Microsoft's docs say it directly: the query variable itself takes no action and returns no data. This is . The work happens only when something enumerates the query: a foreach, or an operator that needs real values, such as Count, Any, First, Sum or ToList. Your own iterator methods behave the same way: calling a method written with yield return runs none of its body until someone enumerates the result, and then runs it again for every new enumeration.

Every enumeration runs it again

The results aren't stored anywhere. In the words of the CA1851 rule, the enumeration result isn't calculated once and cached, like Lazy<T>. Each enumeration reads the source again and calls every lambda again, with three consequences:

  • Repeated cost: each pass repeats all the filtering and projection. The CA1851 docs show Count() followed by Last() on a projected sequence costing two full passes. With EF Core, a query is sent to the database whenever its results are consumed, so Any(), Count() and a foreach on the same IQueryable are three round trips.
  • Changing results: the query sees the source as it is when it runs, not when it was written. If items were added in between, the passes disagree, like 1,204 versus 1,207.
  • Repeated side effects: a Select that logs, sends an email or calls Guid.NewGuid() does it again on every pass, and the generated values differ each time.

Captured variables are read late, too

Lambdas in a query are : they capture variables, not their current values. The query reads them when it runs:

C# Program.cs
var minTotal = 50;IEnumerable<int> big = new[] { 40, 75, 120 }.Where(t => t > minTotal);minTotal = 100;                 // changed after the query was writtenConsole.WriteLine(big.Count()); // 1: the query reads minTotal when it runs

Exceptions follow the same timing. A Select(int.Parse) written inside a try block doesn't throw there. It throws later, wherever the query is finally enumerated, possibly outside any catch.

Streaming doesn't mean cached

Where and Select are streaming: they process one element at a time as you pull it. OrderBy and GroupBy are nonstreaming: they read the whole source before returning their first element. Both kinds are still deferred, and both start from scratch on the next enumeration.

The export, before and after

Here an in-memory list stands in for the orders table, and calls counts how often the filter runs:

C# Program.cs
var orders = new List<int> { 40, 75, 120 }; // order totals, like a tablevar calls = 0;IEnumerable<int> toExport = orders.Where(total =>{    calls++;                 // counts every filter call    return total > 50;});Console.WriteLine(toExport.Count()); // 2: logged as "Exporting 2 orders"orders.Add(300);                     // a new order arrives meanwhileforeach (var total in toExport){    Console.WriteLine(total);        // 75, 120, 300: three rows written}Console.WriteLine(calls);            // 7: the filter ran on both passes

The fix is one call. ToList() runs the query once and keeps the results in a real list, which is called . The log line and the loop now see the same two orders, and the filter runs 3 times instead of 7. An order that arrives mid-export goes into the next run instead of half of this one.

Myth vs reality

MythReality
An IEnumerable<T> variable holds the query's resultsIt holds the query; results are produced on each enumeration
Iterating twice is freeEach pass reruns the source and every lambda; with IQueryable, another SQL query
The query sees data as it was when writtenIt sees the source and captured variables as they are when it runs
An exception surfaces where the query is writtenIt surfaces where the query is enumerated
ToList() everywhere is the safe fixMaterialize results you reuse; stay lazy for one pass over large data

How to apply it in your project

  1. Turn on CA1851Set dotnet_diagnostic.CA1851.severity = warning in .editorconfig and fix what it reports, starting with code that touches a database or an external service.
  2. Materialize at the boundariesRepositories and services should return finished data, such as List<T>, arrays or IReadOnlyList<T>, not live queries. In EF Core, call ToListAsync() before the data leaves the data layer.
  3. Ask for what you needIf a method needs a count and a loop, take IReadOnlyCollection<T> or IReadOnlyList<T> instead of IEnumerable<T>. Keep IEnumerable<T> parameters for code that reads the sequence exactly once.
  4. Keep query lambdas pureDon't log, send messages, generate IDs or change state inside Where or Select. Do that in a loop over materialized results, where it runs exactly once per item.

Key takeaways

  • A LINQ query in an IEnumerable<T> is a recipe: it holds no data until something enumerates it.
  • Every foreach, Count(), Any() or First() runs the whole query again, including database round trips.
  • The query reads its source, captured variables and failures when it runs, not when it's written.
  • Call ToList() or ToArray() once when you need stable results more than once.
  • Enable CA1851 to catch multiple enumeration, and keep side effects out of query lambdas.

📚 المصادر

  1. Introduction to LINQ Queries (C#) — Microsoft Learn
  2. Deferred execution and lazy evaluation — Microsoft Learn
  3. CA1851: Possible multiple enumerations of IEnumerable collection — Microsoft Learn
  4. How Queries Work (EF Core) — Microsoft Learn

التعليقات (0)