In C#, an IEnumerable<decimal> built with Where and Select over orders is checked with Any(), totalled with Sum() and looped; why does the pricing call repeat, and how do you fix it?
answer
- three consumers, three passes
- a pipeline, not a cache
- side effects repeat with it
- the CA1851 analyzer rule
- materialise once, then reuse
basics
~10 sAny(), Sum() and foreach each enumerate the deferred query separately, so the Where predicate and the pricing selector run again on every pass. Materialise once with ToList() or ToArray() and use the stored results.
solid answer
~40 sA LINQ to Objects query is a pipeline, not a cache. `Any()` enumerates until it finds the first open order, `Sum()` enumerates every element, and the `foreach` enumerates every element again, so for two open orders the `Price` selector runs five times. That wastes time when the selector is expensive and produces wrong results when it has side effects: a counter, a log line, a call that can return a different value next time. The fix is to enumerate once, `var gross = orders.Where(o => o.IsOpen).Select(Price).ToList();`, then use `gross.Count > 0`, `gross.Sum()` and `foreach` over the list. The code-analysis rule CA1851, "Possible multiple enumerations of 'IEnumerable' collection", reports this pattern; it is not enabled by default in .NET 10, so a team turns it on in `.editorconfig`.
code
csharp · 26 linesvar orders = new List<Order> { new(1, 250m, true), new(2, 40m, false), new(3, 900m, true) };
int priceCalls = 0;
decimal Price(Order o) { priceCalls++; return o.Total * 1.2m; } // stands in for a rate lookup
IEnumerable<decimal> gross = orders.Where(o => o.IsOpen).Select(Price);
if (gross.Any()) // pass 1: stops at the first open order
{
decimal total = gross.Sum(); // pass 2: every open order
int lines = 0;
foreach (var g in gross) lines++; // pass 3: every open order again
Console.WriteLine($"{lines} lines");
}
Console.WriteLine($"Price ran {priceCalls} times for 2 open orders");
priceCalls = 0;
List<decimal> grossList = orders.Where(o => o.IsOpen).Select(Price).ToList();
if (grossList.Count > 0) // List<T>.Count: no enumeration
{
decimal total = grossList.Sum();
foreach (var g in grossList) { }
}
Console.WriteLine($"With ToList: Price ran {priceCalls} times");
record Order(int Id, decimal Total, bool IsOpen);go deeper
Remember that every foreach, Count(), Sum() or Any() over a LINQ query runs it again from the start.
Count the passes in code like this and explain why a selector with a side effect fires once per enumeration, not once per element overall.
Diagnose duplicated side effects or inconsistent totals as multiple enumeration, materialise at the right point, and enable CA1851 so the pattern is caught in review.
Decide where a codebase materialises sequences and which parameter types its methods accept, balancing the cost of copies against the risk of repeated work.
## A query is a pipeline, not a cache `orders.Where(o => o.IsOpen).Select(Price)` builds an iterator that, each time it is enumerated, walks `orders`, applies the predicate and calls `Price` for every match. It stores no results. Every consumer that needs elements starts a **new enumeration** from the beginning of the source, and every enumeration re-runs every lambda in the chain. This is called **multiple enumeration**. Microsoft's description of rule CA1851 states the key fact: the enumeration result is not calculated once and cached the way `Lazy<T>` caches a value. ## Counting the passes In the example below there are three orders, two of them open, and `Price` increments a counter: 1. **`gross.Any()`** enumerates until the first element appears: the predicate runs on order 1, which is open, so `Price` runs **once** and `Any()` returns `true`. 2. **`gross.Sum()`** enumerates the whole query: `Price` runs for both open orders, **twice**. 3. **`foreach`** enumerates the whole query again: **twice** more. Total: **five** calls for two orders. With a thousand open orders it would be 2,001 calls, and a `Count()` added for a log line would make it 3,001; the waste grows with every new consumer of the same variable, which is why it often appears gradually as code is edited. After `ToList()`, the same three uses cost **two** calls, because `List<T>.Count`, `Sum()` over the list and `foreach` over the list read stored values. | Consumer | What it does to the query | `Price` calls | |---|---|---| | `Any()` | partial pass, stops at first element | 1 | | `Sum()` | full pass | 2 | | `foreach` | full pass | 2 | | `ToList()` then all three | one full pass, then reads the list | 2 | ## When repeated passes are a bug, not just a cost - **Side effects repeat.** A selector that logs, increments a counter, assigns an id or sends a message does so once per pass. Two passes can mean duplicate audit lines or two ids for the same order. - **Non-deterministic values diverge.** If the selector reads the clock, a random number or a live exchange rate, `Sum()` and the `foreach` can see different values, and the printed lines no longer add up to the printed total. - **The source may change between passes.** Because each pass re-reads the list, an order added between `Sum()` and `foreach` appears in one and not the other. - **Some sources cannot be re-read cheaply.** An `IEnumerable<T>` that wraps a file reader, a network stream or a generator may redo expensive I/O, or fail, on a second enumeration. ## Fixing it - **Materialise once** where the data is defined: `ToList()` or `ToArray()` runs the pipeline one time and stores the elements. Use the stored collection for every later read. - **Use the collection's own members**: `List<T>.Count` or `Length` instead of `Any()` or `Count()` on the query. - **Fold several results into one pass** when memory matters more than clarity, for example a single `foreach` that accumulates the total and writes each line. - **Change parameter types** so they say what they need: a method that enumerates its argument twice can take `IReadOnlyCollection<T>` or `IReadOnlyList<T>`, forcing the caller to pass something already materialised. - **Do not add `ToList()` everywhere defensively**: calling it on a `List<T>` still allocates and copies, and it removes streaming for very large sequences. ## Letting the analyzer find it CA1851 is a performance rule in the .NET code-analysis set, introduced in .NET 7 and, per its documentation page, not enabled by default in .NET 10. Enabling it is one line in `.editorconfig`: ```ini [*.cs] dotnet_diagnostic.CA1851.severity = warning ``` With that line, building the example reports CA1851 on each of the three uses of `gross`. By default its analysis covers the methods in the `System.Linq` namespace, and `.editorconfig` options add custom enumeration methods; its documentation says it is safe to suppress when the underlying object is really a `List<T>` or an array, or when the methods receiving it do not enumerate it. How analyzer severities and warning settings are managed project-wide is covered with compiler warnings and analyzers. ## Summary - Each enumeration of a deferred query re-runs the whole pipeline, side effects included. - `Any()`, `Count()`, `Sum()`, `First()` and `foreach` are separate enumerations. - Materialise once with `ToList()` or `ToArray()` at the point that defines the data, then reuse it. - Turn on CA1851 so builds point out the remaining cases.
- When is it reasonable to suppress CA1851 instead of materialising?When the object behind the `IEnumerable<T>` is already a `List<T>` or an array, so a second pass reads stored elements, or when the method receiving it does not actually enumerate it. Those are the cases the rule's documentation names. A better fix than suppression is often to type the variable or parameter as `IReadOnlyList<T>` or `IReadOnlyCollection<T>`, so the code states that the data is materialised and the analyzer has nothing to report.
- Why not call ToList() on every IEnumerable<T> parameter at the top of a method?It costs an allocation and a full copy every time, even when the caller already passed a list, because `ToList()` on a `List<T>` builds a new list. It also forces a whole sequence into memory, which defeats a caller that streams a very large or unbounded source. Materialise where the query is defined, or ask for a collection type in the signature, rather than copying defensively on every call.
- A LINQ query stores its results after the first enumeration
- Any() before a foreach costs nothing on a filtered query
- Multiple enumeration only matters for database queries, never in memory
- CA1851 is on by default, so the build would already warn
- Typing the variable as IEnumerable<T> makes it hold the results