
Your IEnumerable Holds No Data: LINQ Deferred Execution and Multiple Enumeration
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
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
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
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 byLast()on a projected sequence costing two full passes. With EF Core, a query is sent to the database whenever its results are consumed, soAny(),Count()and aforeachon the sameIQueryableare 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 Selectthat logs, sends an email or callsGuid.NewGuid()does it again on every pass, and the generated values differ each time.
Captured variables are read late, too
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 runsSelect(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
calls counts how often the filter runs:
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 passesvar orders = new List<int> { 40, 75, 120 }; // order totals, like a tablevar calls = 0;List<int> toExport = orders.Where(total =>{ calls++; // counts every filter call return total > 50;}).ToList(); // run the query once, keep the resultsConsole.WriteLine(toExport.Count); // 2: logged as "Exporting 2 orders"orders.Add(300); // goes into the next exportforeach (var total in toExport){ Console.WriteLine(total); // 75, 120: two rows written}Console.WriteLine(calls); // 3: one pass over three ordersToList() 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
IEnumerable<T> variable holds the query's results | |
IQueryable, another SQL query | |
ToList() everywhere is the safe fix |
How to apply it in your project
Turn on CA1851 Set dotnet_diagnostic.CA1851.severity = warningin.editorconfigand fix what it reports, starting with code that touches a database or an external service.Materialize at the boundaries Repositories and services should return finished data, such as List<T>, arrays orIReadOnlyList<T>, not live queries. In EF Core, callToListAsync()before the data leaves the data layer.Ask for what you need If a method needs a count and a loop, take IReadOnlyCollection<T>orIReadOnlyList<T>instead ofIEnumerable<T>. KeepIEnumerable<T>parameters for code that reads the sequence exactly once.Keep query lambdas pure Don't log, send messages, generate IDs or change state inside WhereorSelect. 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()orFirst()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()orToArray()once when you need stable results more than once.Enable CA1851 to catch multiple enumeration, and keep side effects out of query lambdas.
التعليقات (0)