C# Reference ยท LINQ
LINQ pitfalls
Reference for common LINQ mistakes in C#: multiple enumeration, deferred execution surprises, changing a list during a query, and Single or First exceptions.
Most LINQ bugs come from one fact: a query is a recipe, not a result. Nothing runs until you enumerate it, and every enumeration runs the recipe again. That single idea explains multiple enumeration, queries that "see" later changes to their source, and side effects that happen at surprising times.
The other group of pitfalls are exceptions that the "safe-looking" methods throw: First, Single, Max and Average on empty input, and modifying a collection while a query is walking it. This page shows each problem with a runnable example and the fix.
var query = items.Where(x => Expensive(x)); // nothing has run yet int a = query.Count(); // runs Expensive for every item int b = query.Count(); // runs it all again
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Usage notes
- Multiple enumeration. Each
Count(),Sum(),foreachorToList()on a lazy query runs it again. If the source is expensive (a database, a file, a network call, ayieldmethod with side effects), callToList()orToArray()once and reuse that. Analyzers warn about this as "possible multiple enumeration". - Accept the right parameter type. A method that takes
IEnumerable<T>and loops over it twice invites the problem. TakeIReadOnlyCollection<T>orIReadOnlyList<T>if you need a count or indexing, or materialize inside the method. - Deferred queries see later changes. A query reads its source when it runs. If you want a point-in-time copy, materialize it. This is also why a query returned from a method may behave differently from one you materialized.
- Captured variables are live. A lambda captures the variable itself, not its value at that moment. Changing the variable before the query runs changes the result. Loop variables of
forloops are a classic trap: copy them into a local first. - Side effects in
SelectandWhere. They run once per enumeration and in an order you do not control for operators that buffer. Useforeachfor side effects and keep query lambdas pure. - Do not change a collection while a query over it runs.
List<T>throwsInvalidOperationException("Collection was modified; enumeration operation may not execute.") on the next step. Materialize first, or build a new list. FirstandSinglethrow on an empty (and, forSingle, on a multi-item) result. UseFirstOrDefaultorSingleOrDefaultwhen "none" is a normal case, andSinglewhen more than one is a bug you want to hear about. Remember thatFirstOrDefaultreturnsdefault(T), which is0forint; cast to a nullable type or useAnyfirst when0is a valid value. Since .NET 6 there are overloads that take your own default:FirstOrDefault(predicate, fallback).- Empty-sequence aggregates.
Sumof an empty sequence is0, butMax,MinandAverageof an empty sequence of non-nullable values throw. UseDefaultIfEmpty, or aggregate nullable values (the result is thennull). ToDictionarythrows on duplicate keys. UseToLookuporGroupBywhen keys can repeat.- Order of
OrderBy/ThenBy. A secondOrderByreplaces the first sort instead of refining it; useThenByfor secondary keys. - Boxing and closures in hot code are covered in LINQ performance.