Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Using SingleOrDefault in C# LINQ

Learn how SingleOrDefault works in C# LINQ: what it returns for empty or duplicate matches, when it throws InvalidOperationException, and how it compares to FirstOrDefault.

~6 min readC#
#C##LINQ#SingleOrDefault#Exception Handling
A diagram showing how SingleOrDefault in C# LINQ returns one element, returns the default for an empty match, and throws an exception for multiple matches.

When you query a collection and expect either no match or exactly one match, SingleOrDefault lets you express that expectation directly. It returns the single matching element, returns the type's default value when nothing matches, and throws an InvalidOperationException when more than one element matches.

What SingleOrDefault Actually Returns

SingleOrDefault is an extension method defined in the System.Linq namespace. It evaluates the entire sequence and applies a predicate when one is provided. The method has three possible outcomes:

  • If exactly one element matches, that element is returned.
  • If no element matches, the default value for the element type is returned.
  • If more than one element matches, an InvalidOperationException is thrown.

The default value depends on the element type. For reference types and nullable value types, the default is null. For non-nullable value types such as int, bool, or DateTime, the default is the zero-initialized value: 0, false, or DateTime.MinValue respectively.

Basic Syntax and Minimal Example

The simplest form of the method takes no arguments and returns the only element of the sequence:

csharp
var items = new List<string> { "alpha" }; string only = items.SingleOrDefault(); Console.WriteLine(only); // alpha

The predicate form filters the sequence first:

csharp
var users = new List<User> { new User { Id = 1, Email = "alice@example.com" }, new User { Id = 2, Email = "bob@example.com" } }; User match = users.SingleOrDefault(u => u.Email == "alice@example.com");

When the predicate matches exactly one user, match holds that User instance. When no user matches, match is null because User is a reference type. This makes the predicate form useful for lookups where the key is expected to be unique, such as an email address or an order number.

The Three Possible Outcomes in Practice

The behavior differs meaningfully between an empty result and a duplicate result. Consider this sequence:

csharp
var orders = new List<Order> { new Order { Number = "A-100", CustomerId = 7 }, new Order { Number = "B-200", CustomerId = 7 } }; Order duplicate = orders.SingleOrDefault(o => o.CustomerId == 7);

Here two orders belong to customer 7, so the call throws InvalidOperationException rather than returning a value. That exception is the method's way of telling you that your assumption about the data is wrong: you expected at most one match, but the data violates that expectation.

An empty match behaves differently:

csharp
Order missing = orders.SingleOrDefault(o => o.CustomerId == 99); // missing is null

The method cannot distinguish between "no match" and "the matched element happened to be null" when the element type is a reference type. If your predicate can match a null element, you cannot tell those two cases apart without additional checks.

SingleOrDefault vs FirstOrDefault vs Single

The three methods are easy to confuse because their names are similar, but their contracts differ in ways that matter at runtime.

MethodEmpty sequenceOne matchMultiple matches
SingleOrDefaultReturns defaultReturns the elementThrows
FirstOrDefaultReturns defaultReturns the elementReturns first match
SingleThrowsReturns the elementThrows

FirstOrDefault stops enumerating as soon as it finds the first match. SingleOrDefault cannot stop early because it must verify that no second match exists. That difference is not just about behavior; it also affects runtime cost.

Use SingleOrDefault when the data is expected to be unique by constraint, such as a primary key lookup or a unique business identifier. Use FirstOrDefault when multiple matches are acceptable and you only care about the first one, such as the first matching entry in a list that has already been ordered by timestamp.

When SingleOrDefault Throws InvalidOperationException

The exception is thrown in two situations: when the sequence contains more than one matching element, and when the sequence itself contains more than one element in the parameterless form. The parameterless form is rarely useful in practice because it requires the entire collection to have exactly one element.

A common source of unexpected exceptions is a predicate that is not selective enough. For example:

csharp
var active = users.SingleOrDefault(u => u.IsActive);

If two users are marked active, this throws. The fix is either to tighten the predicate so it targets a unique value, or to switch to FirstOrDefault when the first active user is acceptable.

Another source is a collection that appears unique in tests but contains duplicates in production because of data imported from an external system. In that situation, the exception is useful because it surfaces a data integrity problem early rather than silently picking one of several rows.

Performance and Runtime Cost

SingleOrDefault must keep enumerating after the first match to verify that no second match exists. This is the main runtime difference from FirstOrDefault, which stops at the first match. For small in-memory collections the difference is usually negligible, but for large sequences or lazily evaluated remote sources the cost can be significant.

When the source is a lazily evaluated IEnumerable<T> over a database query, the data source may need to provide enough rows to verify uniqueness. If you are using IQueryable<T>, the query provider may translate SingleOrDefault into its own query plan, so the behavior depends on the provider and the schema. If you know the underlying data has a unique constraint, you can often replace SingleOrDefault with FirstOrDefault to avoid the extra scan, but only when the contract allows it. If uniqueness is a requirement of your logic, removing the uniqueness check changes the behavior of the code.

There is no way to make SingleOrDefault stop as soon as it finds one match, because stopping early would prevent it from detecting a second match. A custom loop can make the duplicate check explicit, but it still has to keep scanning when exactly one match exists, because a second match could appear later:

csharp
static T? SingleOrDefaultFast<T>(IEnumerable<T> source, Func<T, bool> predicate) { T? found = default; bool hasMatch = false; foreach (var item in source) { if (!predicate(item)) continue; if (hasMatch) { throw new InvalidOperationException("More than one match found."); } found = item; hasMatch = true; } return hasMatch ? found : default; }

This custom loop produces the same return values and exception type as the built-in method. It also has the same limitation: when exactly one element matches, it must scan the rest of the sequence to confirm that no second match exists. The only way to avoid that scan is to rely on an index or a unique constraint at the data source.

Null Handling and Default Value Pitfalls

When the element type is a reference type, SingleOrDefault returns null for an empty match. This creates an ambiguity when the predicate can match a null element. Consider:

csharp
var entries = new List<string?> { null, "alpha" }; string? result = entries.SingleOrDefault(e => e == null);

Here the predicate matches exactly one element, which is null, so the method returns null. The caller cannot tell whether this means "no match" or "the match was null". If that distinction matters, you need to check the count separately or use a different approach, such as filtering with Where and then inspecting the result.

For value types, the default value is also a valid value. For example, int has a default of 0, so a call that returns 0 could mean either "no match" or "the matched element was 0". When 0 is a meaningful value in your domain, use a nullable type or check the count explicitly.

Practical Usage Patterns

The most common practical use is a lookup where the key is unique by design:

csharp
var account = accounts.SingleOrDefault(a => a.AccountNumber == input); if (account is null) { return NotFound(); } return Ok(account);

This pattern is clear and expresses the uniqueness expectation in the query itself. Another common use is configuration lookup where a default is acceptable:

csharp
var timeout = settings.SingleOrDefault(s => s.Key == "Timeout")?.Value ?? "30";

The null-conditional operator combined with the null-coalescing operator handles the empty case cleanly.

A less obvious use is validation: the exception thrown by SingleOrDefault can serve as an assertion that a collection has exactly one element. However, relying on exceptions for control flow is generally discouraged. If you expect the collection to contain exactly one element and the empty case is an error, prefer Single so the exception message and behavior are explicit.

Maintainability and Readability Considerations

SingleOrDefault communicates intent better than a manual loop. A reader sees the method name and immediately understands that the code expects zero or one match. That implicit documentation is valuable in codebases where data uniqueness is not obvious.

The flip side is that the method hides the exception path. A developer who does not know the method's contract may be surprised when it throws on duplicate data. Documenting the assumption in a comment, or better, by naming the variable clearly, reduces that surprise:

csharp
// Expects at most one active subscription per account. var subscription = subscriptions.SingleOrDefault(s => s.AccountId == id && s.IsActive);

When the data source is a database, the uniqueness assumption should match a real constraint in the schema. If the schema does not enforce uniqueness, the LINQ call may work in development and fail in production when duplicate rows appear. Aligning the code's assumption with the database constraint prevents that class of failure.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.