# InvalidOperationException: Sequence contains no elements / more than one element

**Code:** `Sequence contains no elements` · **Category:** .NET · **Seen on:** .NET

LINQ `First()`, `Single()`, `Last()` or `Max()` ran on an empty sequence (or `Single()` found several items).

## Meaning

`First()`/`Single()` assert that data exists. When “no result” is a valid case, use the `…OrDefault()` variants and handle null.

## Common causes

- Query returned no rows but code used First()/Single()
- Single() on data that has duplicates
- Max()/Min()/Average() on an empty collection

## Quick fix

1. Use FirstOrDefault/SingleOrDefault and null-check
2. Use `DefaultIfEmpty()` before aggregates, or `Max()` on nullable projections
3. Use Single only when uniqueness is guaranteed by a constraint

## Detailed fix by platform

### .NET

1. Safe patterns:

```csharp
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == email);
if (user is null) return NotFound();

decimal? maxTotal = await db.Orders.Where(o => o.UserId == id).MaxAsync(o => (decimal?)o.Total);
```


## How to diagnose

1. **Method** — First/Single/Max?
2. **Data** — Should empty be possible?
3. **Uniqueness** — Duplicates where Single expects one?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/dotnet/sequence-contains-no-elements)
