Skip to content
Tutorials Center
My learning

Topics

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.

C#
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

C# Multiple enumeration and late evaluation

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.

C# Exceptions from First, Single, Max and changing the source

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(), foreach or ToList() on a lazy query runs it again. If the source is expensive (a database, a file, a network call, a yield method with side effects), call ToList() or ToArray() 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. Take IReadOnlyCollection<T> or IReadOnlyList<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 for loops are a classic trap: copy them into a local first.
  • Side effects in Select and Where. They run once per enumeration and in an order you do not control for operators that buffer. Use foreach for side effects and keep query lambdas pure.
  • Do not change a collection while a query over it runs. List<T> throws InvalidOperationException ("Collection was modified; enumeration operation may not execute.") on the next step. Materialize first, or build a new list.
  • First and Single throw on an empty (and, for Single, on a multi-item) result. Use FirstOrDefault or SingleOrDefault when "none" is a normal case, and Single when more than one is a bug you want to hear about. Remember that FirstOrDefault returns default(T), which is 0 for int; cast to a nullable type or use Any first when 0 is a valid value. Since .NET 6 there are overloads that take your own default: FirstOrDefault(predicate, fallback).
  • Empty-sequence aggregates. Sum of an empty sequence is 0, but Max, Min and Average of an empty sequence of non-nullable values throw. Use DefaultIfEmpty, or aggregate nullable values (the result is then null).
  • ToDictionary throws on duplicate keys. Use ToLookup or GroupBy when keys can repeat.
  • Order of OrderBy/ThenBy. A second OrderBy replaces the first sort instead of refining it; use ThenBy for secondary keys.
  • Boxing and closures in hot code are covered in LINQ performance.