Handling 'Sequence has no elements' Exception
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The .NET message Sequence contains no elements is one of the most common LINQ failures. It appears when code asks for an element that does not exist, usually because the sequence is empty and the operator assumes at least one value will be present.
Why LINQ Throws This Exception
Several LINQ operators encode a strict contract. First(), Last(), and Single() all promise to return an actual element, not an optional result. If the source contains nothing, LINQ throws InvalidOperationException instead of guessing what the caller wanted.
The simplest example is First() on an empty array:
That code compiles, but it fails at runtime because numbers has no first element. The exception is useful because it exposes a mismatch between the code and the data.
This is why the real fix is almost never "catch the exception everywhere." The real fix is choosing an operator that matches the business rule.
Pick the Operator That Matches the Contract
Before changing code, ask what empty input means in this path.
If empty data is valid, use an operator that can represent "no result":
If the result must exist, keep First() or Single() and fail early with a better message:
That produces an error that explains the violated invariant instead of leaking a generic LINQ message.
First, Single, and FirstOrDefault Mean Different Things
A lot of bugs come from treating these methods as interchangeable.
- '
First()means at least one item must exist.' - '
Single()means exactly one item must exist.' - '
FirstOrDefault()means zero or more items may exist, and an empty sequence should return a default value.'
Consider a user lookup:
Here SingleOrDefault() is appropriate only if the email must be unique. If duplicates are possible and you simply need one row, FirstOrDefault() is the better operator.
Watch Out for Value-Type Defaults
FirstOrDefault() is safer for empty sequences, but it introduces another design decision. The default value for a value type might be a valid business value, which can hide mistakes.
When that ambiguity matters, project to a nullable value:
Now the absence of data is distinguishable from a real 0.
Empty Sequences in Database Queries
This issue frequently appears in EF Core or other IQueryable code because developers assume a row exists.
That is more robust than:
Use the strict version only if a missing row means corrupted state or a broken invariant.
Prefer Prevention Over Catching
You can catch the exception, but it is usually a boundary concern rather than the core fix.
This can be reasonable in an API or service layer that translates low-level errors into domain language. Even there, it is better to structure the query so the empty case is handled intentionally.
Common Pitfalls
- Replacing
First()withSingle()without understanding thatSingle()also throws on empty input and on duplicates. - Using
FirstOrDefault()and then forgetting that0,false, orDateTime.MinValuemay be ambiguous. - Calling
Any()and thenFirst()on an expensive query when a single well-chosen operator would be clearer. - Letting repository or controller code assume that database lookups always return a row.
- Catching
InvalidOperationExceptionbroadly and masking unrelated failures.
Summary
- '
Sequence contains no elementsmeans the code required an item from an empty sequence.' - The right fix is to choose the LINQ operator that matches the real data contract.
- '
FirstOrDefault()is useful when an empty result is valid, but default values can be ambiguous.' - '
Single()should be used only when exactly one element is required.' - Handle emptiness intentionally at the query boundary instead of treating the exception as normal control flow.
Related reading
- Handling warning for possible multiple enumeration of IEnumerable
- Hangfire Background Job with Return Value
- Has this usage of async / await in C been discovered before?
- `Hash` Password in C? Bcrypt/PBKDF2
- Hard reset of a single file
- Has an event handler already been added?
- HashSetT versus DictionaryK, V w.r.t searching time to find if an item exists
- Haskell equivalent of C 5 async/await

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.