2.9 — First vs FirstOrDefault vs Single vs SingleOrDefault¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.8 Advanced LINQ operators · Next: 2.10 Threads vs Tasks
Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
First= "give me the first match, and there had better be one."Single= "there must be exactly one match — throw if there are none or more than one."...OrDefault= "returnnullinstead of throwing when there is nothing."Singleis slower, because to prove there is only one it must keep looking after it finds one.
The concept¶
All four answer "get me one item from this sequence". They differ in what counts as wrong.
Think of it as asking a room full of people a question:
First— "someone put your hand up." You take the first hand you see and stop looking. If nobody responds, that is an error.FirstOrDefault— same, but if nobody responds you shrug and carry on with nothing.Single— "exactly one of you should have your hand up." You must scan the whole room to be sure nobody else did. Two hands is an error. Zero hands is an error.SingleOrDefault— same scan, but zero hands is acceptable. Two is still an error.
That "scan the whole room" difference is the performance point, and it is the half of the answer most candidates miss.
How it works¶
The four in a table¶
| Method | 0 matches | 1 match | 2+ matches | Stops early? |
|---|---|---|---|---|
First() |
throws | returns it | returns the first | ✅ |
FirstOrDefault() |
null / default |
returns it | returns the first | ✅ |
Single() |
throws | returns it | throws | ❌ |
SingleOrDefault() |
null / default |
returns it | throws | ❌ |
Both First variants stop the moment they find a match. Both Single variants keep going,
because finding a second match is the only way to know it should throw.
var orders = new List<Order> { a, b, c };
orders.First(); // a
orders.First(o => o.Total > 1_000_000); // InvalidOperationException:
// "Sequence contains no matching element"
orders.FirstOrDefault(o => o.Total > 1_000_000); // null
orders.Single(); // InvalidOperationException:
// "Sequence contains more than one element"
orders.Single(o => o.Id == a.Id); // a — exactly one match, fine
The performance difference, concretely¶
// A table with 1,000,000 orders, one matching row
db.Orders.First(o => o.Id == id);
// SQL: SELECT TOP 1 * FROM Orders WHERE Id = @id
// Stops at the first row found.
db.Orders.Single(o => o.Id == id);
// SQL: SELECT TOP 2 * FROM Orders WHERE Id = @id
// Fetches TWO rows so it can tell whether a second one exists.
TOP 2 rather than TOP 1. On an indexed primary key the difference is trivial. On an
unindexed column where the match is rare, Single may scan a great deal more.
default is not always null¶
...OrDefault returns default(T), which depends on the type
(1.1):
List<Order> empty = [];
empty.FirstOrDefault(); // null — Order is a class
List<int> emptyInts = [];
emptyInts.FirstOrDefault(); // 0 — NOT null! int is a value type
That second case is a genuine bug source:
var total = amounts.FirstOrDefault();
if (total == 0)
{
// Is this "nothing found" or "found a zero"?
// You cannot tell. They are indistinguishable.
}
Fixes:
// .NET 6+ — supply your own fallback
var total = amounts.FirstOrDefault(-1);
// Or make the sequence nullable so null means "missing"
int? total = amounts.Cast<int?>().FirstOrDefault();
// Or check separately
if (amounts.Any())
var total = amounts.First();
The related pair: Last and ElementAt¶
orders.Last(); // throws if empty
orders.LastOrDefault(); // null if empty
orders.ElementAt(3); // throws if out of range
orders.ElementAtOrDefault(3); // null if out of range
⚠️ Last() on an IEnumerable walks the entire sequence to reach the end. Against a
database, prefer OrderByDescending(...).First() — that becomes ORDER BY ... DESC TOP 1,
which the database can satisfy from an index.
Which to use¶
The choice should describe what you believe about your data, and that is the answer an interviewer is listening for.
// Looking up by primary key — exactly one row must exist, or the data is corrupt.
// Single documents that expectation and will tell you loudly if it breaks.
var order = await db.Orders.SingleAsync(o => o.Id == id, ct);
// Looking up by a unique-ish key that may legitimately be missing
var user = await db.Users.SingleOrDefaultAsync(u => u.Email == email, ct);
if (user is null) return NotFound();
// Getting the newest of many — several exist, you want one
var latest = await db.Orders
.Where(o => o.CustomerId == id)
.OrderByDescending(o => o.CreatedAt)
.FirstAsync(ct);
// Optional lookup where absence is normal
var discount = discounts.FirstOrDefault(d => d.Code == code);
var amount = discount?.Amount ?? 0;
The rule: use Single when more than one would mean a bug. It is a runtime assertion of
a data invariant. Using First there would silently pick one and hide the duplicate,
possibly for years.
Code¶
The pattern that shows up constantly in ASP.NET Core controllers:
[HttpGet("{id:guid}")]
public async Task<IActionResult> Get(Guid id, CancellationToken ct)
{
// SingleOrDefault: the ID is a primary key so at most one row can match,
// but the client may well ask for one that does not exist.
var order = await _db.Orders
.AsNoTracking()
.SingleOrDefaultAsync(o => o.Id == id, ct);
if (order is null)
return NotFound(); // a normal outcome, not an exception
return Ok(_mapper.ToDto(order));
}
Why not First here? Because if a duplicate ID ever appeared, First would quietly return
one of them and you would never find out. Single turns that into a loud failure.
Why not Single (without OrDefault)? Because "the client asked for an ID that does not
exist" is normal traffic, not an error. Throwing an exception for it would be using
exceptions for control flow, which is slow and noisy in your logs
(1.20).
The general shape: SingleOrDefault plus an explicit null check plus a 404.
Interview questions¶
Q: What is the difference between First and Single?
First returns the first matching item and stops looking, throwing only if there are no
matches at all. Single insists there is exactly one match — it throws if there are none and
also if there is more than one. Because it has to prove uniqueness, it cannot stop at the
first match; it keeps reading to check nothing else qualifies. Against a database that shows
up as TOP 2 instead of TOP 1. So they differ both in meaning and in cost.
Q: When would you choose Single over First?
When more than one match would mean the data is wrong. Looking a row up by its primary key
is the clearest case — two rows with the same key means something is broken, and I want to
know rather than silently work with an arbitrary one of them. Single acts as a runtime
assertion of that invariant. If several matches are legitimate and I just want one of them —
the most recent order, say — then First after an OrderBy is correct and cheaper.
Q: What does FirstOrDefault return for a list of int?
Zero, not null, because default(int) is zero. That is a real trap, because you then cannot
distinguish "nothing matched" from "matched a value that happens to be zero". The fixes are
to pass an explicit fallback using the .NET 6 overload, to project to a nullable type so
null genuinely means missing, or to check Any() separately before calling First.
Q: Which would you use in a controller looking up by ID, and why?
SingleOrDefault, followed by an explicit null check returning 404. Single documents that
the ID is unique, so a duplicate would throw rather than silently return one row. The
OrDefault part matters because a client requesting a non-existent ID is completely normal
traffic — turning that into an exception would be using exceptions for control flow, which is
expensive and fills your logs with errors that are not errors.
Traps ⚠️¶
First()on an empty sequence throws, it does not return null. The exception message — "Sequence contains no elements" — tells you nothing about which query failed.FirstOrDefault()on a value type returns 0 orfalse, not null. You cannot tell "missing" from "legitimately zero".Singlecosts more thanFirst. It must keep reading to prove uniqueness.- Using
FirstwhereSinglebelongs hides duplicate data, potentially for years. Last()on anIEnumerablewalks the whole sequence. UseOrderByDescending(...).First()against a database.- The exception messages are unhelpfully generic. In a method with several queries you
cannot tell which one threw. Prefer
SingleOrDefaultplus your own descriptive exception. - Use the
Asyncversions with EF Core —SingleOrDefaultAsync,FirstOrDefaultAsync. The synchronous ones block a thread. See 2.13.
Related¶
- 2.5 LINQ basics — the other element operators
- 2.6 Deferred execution — these all execute immediately
- 1.1 Value vs reference types — why
defaultdiffers - 1.20 Exceptions — why not to use them for control flow
- 10.3 Status codes — returning 404 properly