exception-handling
sequence-error
programming
.net
csharp

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.

Browse interview questions

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:

csharp
1using System;
2using System.Linq;
3
4var numbers = Array.Empty<int>();
5var first = numbers.First();
6
7Console.WriteLine(first);

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":

csharp
1using System;
2using System.Linq;
3
4var numbers = Array.Empty<int>();
5var first = numbers.FirstOrDefault();
6
7Console.WriteLine(first); // 0

If the result must exist, keep First() or Single() and fail early with a better message:

csharp
1using System;
2using System.Linq;
3
4string[] users = Array.Empty<string>();
5
6if (!users.Any())
7{
8    throw new InvalidOperationException("Expected at least one user before selecting the first item.");
9}
10
11Console.WriteLine(users.First());

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:

csharp
1using System;
2using System.Linq;
3
4var users = new[]
5{
6    new User(1, "[email protected]"),
7    new User(2, "[email protected]")
8};
9
10var match = users.SingleOrDefault(u => u.Email == "[email protected]");
11
12Console.WriteLine(match is null ? "not found" : match.Email);
13
14record User(int Id, string Email);

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.

csharp
1using System;
2using System.Linq;
3
4var scores = Array.Empty<int>();
5var score = scores.FirstOrDefault();
6
7if (score == 0)
8{
9    Console.WriteLine("This could mean the sequence was empty or the first score was really zero.");
10}

When that ambiguity matters, project to a nullable value:

csharp
1using System;
2using System.Linq;
3
4var scores = Array.Empty<int>();
5int? score = scores.Select(x => (int?)x).FirstOrDefault();
6
7Console.WriteLine(score.HasValue ? score.Value : -1);

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.

csharp
1var customer = db.Customers
2    .Where(c => c.Email == email)
3    .FirstOrDefault();
4
5if (customer is null)
6{
7    return Results.NotFound();
8}
9
10return Results.Ok(customer);

That is more robust than:

csharp
var customer = db.Customers.First(c => c.Email == email);

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.

csharp
1try
2{
3    return numbers.First();
4}
5catch (InvalidOperationException ex)
6{
7    throw new ApplicationException("The data source was empty when a value was required.", ex);
8}

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() with Single() without understanding that Single() also throws on empty input and on duplicates.
  • Using FirstOrDefault() and then forgetting that 0, false, or DateTime.MinValue may be ambiguous.
  • Calling Any() and then First() 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 InvalidOperationException broadly and masking unrelated failures.

Summary

  • 'Sequence contains no elements means 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.