In C# LINQ, when do First, FirstOrDefault, Single and SingleOrDefault each throw, and which one suits a lookup by unique key?
answer
- zero, one or more matches
- OrDefault forgives only zero
- Single keeps reading after a match
- InvalidOperationException with four messages
basics
~10 sFirst throws InvalidOperationException when nothing matches; FirstOrDefault returns default instead. Single also throws when a second match exists, and SingleOrDefault still throws on two matches: the OrDefault suffix forgives zero matches, never several.
solid answer
~50 sAll four live on `Enumerable` and differ on two cases. With **no** match, `First` and `Single` throw `InvalidOperationException` ("Sequence contains no matching element" for the predicate overloads) while `FirstOrDefault` and `SingleOrDefault` return `default(T)`: `null` for a reference type, `0` for an `int`, or a value you pass to the `defaultValue` overload. With **two or more** matches, `First` and `FirstOrDefault` return the first one, but `Single` and `SingleOrDefault` both throw ("Sequence contains more than one matching element"). So `Single` asserts that the data is unique and pays for it: it keeps reading after the first match to prove there is no second. For a lookup by a key that must be unique, such as an employee's email, `SingleOrDefault` states that rule and fails loudly when the data breaks it; `FirstOrDefault` is the choice when duplicates are legal and any one will do.
code
csharp · 27 linesusing System;
using System.Collections.Generic;
using System.Linq;
var staff = new List<Employee>
{
new("Ana", "[email protected]", "Payroll"),
new("Ben", "[email protected]", "Payroll"),
new("Ben", "[email protected]", "Legal"),
};
Console.WriteLine(staff.First(e => e.Dept == "Payroll").Name); // Ana
Console.WriteLine(staff.FirstOrDefault(e => e.Dept == "IT") is null); // True
Console.WriteLine(staff.Single(e => e.Email == "[email protected]").Name); // Ana
Console.WriteLine(staff.SingleOrDefault(e => e.Email == "[email protected]") is null); // True
try { staff.SingleOrDefault(e => e.Name == "Ben"); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
try { staff.First(e => e.Dept == "IT"); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
int[] none = [];
Console.WriteLine(none.FirstOrDefault()); // 0, not null
Console.WriteLine(none.FirstOrDefault(-1)); // -1
record Employee(string Name, string Email, string Dept);go deeper
Recite the table: no match throws for First and Single, defaults for the OrDefault forms, and two matches throw for both Single forms. Know default is null or zero.
Explain that Single must keep reading after its first match, name the four exception messages, and say what default(T) gives for a value type versus a reference type.
Treat a Single exception in a log as a data-integrity signal, not a nuisance; choose the operator to encode whether a key is unique and whether absence is an error.
Push teams to state uniqueness rules in code and storage together, so Single guards an invariant the data layer also enforces rather than masking it with FirstOrDefault.
## The four operators side by side `First`, `FirstOrDefault`, `Single` and `SingleOrDefault` are extension methods on `System.Linq.Enumerable`. Each has an overload without a predicate (look at the whole sequence) and one with a `Func<TSource, bool>` predicate (look only at matching elements). They answer the same question, "give me one element", but they disagree about what to do when the sequence holds zero or several candidates. | Operator | No match | Exactly one | Two or more | |---|---|---|---| | `First` | throws `InvalidOperationException` | returns it | returns the first | | `FirstOrDefault` | returns `default(T)` | returns it | returns the first | | `Single` | throws `InvalidOperationException` | returns it | throws `InvalidOperationException` | | `SingleOrDefault` | returns `default(T)` | returns it | throws `InvalidOperationException` | The last row is the one candidates get wrong: the **OrDefault** suffix only changes the zero-match case. `SingleOrDefault` on a sequence with two matches throws exactly like `Single`. ## The exception messages tell you which rule broke Four of the messages in the runtime's `System.Linq` resources come from these operators, each on an `InvalidOperationException`: - "Sequence contains no elements": `First()` or `Single()` without a predicate on an empty sequence. - "Sequence contains no matching element": the predicate overloads found nothing. - "Sequence contains more than one element": `Single()` or `SingleOrDefault()` without a predicate on a sequence of two or more. - "Sequence contains more than one matching element": the predicate overloads found a second match. When a production log shows the last message, the code was right to use `Single`: it has caught duplicate data, and the fix belongs in the data or in a uniqueness constraint, not in swapping the call for `First`. ## What default means `default(T)` depends on the element type: - a reference type such as a `record` or `string` gives `null`, which is why the return type is annotated `TSource?` and nullable analysis warns when you dereference it; - a value type gives its zero value: `0` for `int`, `0m` for `decimal`, a zeroed struct for a `record struct`; - the overloads `FirstOrDefault(defaultValue)` and `SingleOrDefault(predicate, defaultValue)` return the value you pass, which helps when `0` is a legal element and cannot double as "not found". An `int[]` that is empty returns `0` from `FirstOrDefault()`, indistinguishable from a real zero, so code that must tell the two apart passes a sentinel or checks `Any()` first. ## Single costs a longer scan `First` stops at the first match. `Single` cannot: after it finds a match it keeps reading the rest of the sequence to prove no second match exists, and it stops early only when it finds one and throws. On a list of 100,000 employees, `First(e => e.Email == x)` may touch one element while `Single` with the same predicate always reads all 100,000 when the data is clean. That is usually a fair price for the guarantee on an in-memory list, but it is worth knowing when the source is a large or expensive sequence. ## Choosing for a lookup 1. If the key **must** be unique and a missing key is an error, use `Single`: both failures surface as exceptions. 2. If the key must be unique but may be absent, use `SingleOrDefault` and check for `null`. 3. If several matches are legal and any one will do, or the sequence is ordered and you want the head, use `First` or `FirstOrDefault`. 4. If you look up by key many times, build a `Dictionary` or a lookup once instead of scanning with any of the four on every call. ## Common mistakes - Using `FirstOrDefault` everywhere "to be safe": duplicate rows are silently resolved by whichever came first. - Catching the exception from `First` to mean "not found" instead of calling `FirstOrDefault`. - Forgetting that `FirstOrDefault` on a value type never returns `null`. - Writing `Where(predicate).First()` and believing it costs more than `First(predicate)`; both stop at the first match.
- Does Where(predicate).First() enumerate more than First(predicate)?No. `Where` is deferred and streams, so `First` pulls elements through the filter only until the first one passes, the same number of predicate calls as `First(predicate)`. The difference is a small wrapper object, not extra work over the data. The same holds for `Single`: both forms read until the end or until a second match.
- An employee lookup by email logs "Sequence contains more than one matching element"; is switching to FirstOrDefault the fix?Usually not. The message comes from `Single` or `SingleOrDefault` finding a second match, which means two employees share an email the code assumed unique. Switching to `FirstOrDefault` hides the duplicate and returns whichever record happens to come first. Fix the data, enforce uniqueness where the records are created, and keep `Single` as the guard.
- How do you tell an empty int array from one whose first element is 0 when using FirstOrDefault?`FirstOrDefault()` returns `0` in both cases, because `default(int)` is `0`. Pass a sentinel to the `FirstOrDefault(defaultValue)` overload, such as `-1` when salaries or ids are never negative, or test `Any()` first, or project to `int?` with `Select(x => (int?)x)` so an empty sequence yields `null`.
- SingleOrDefault returns null when two elements match
- Switching Single to FirstOrDefault is the fix for a duplicate-match exception
- FirstOrDefault on an int sequence returns null when empty
- Single stops reading as soon as it finds a match
- Catching InvalidOperationException from First is the normal not-found check