Sequence contains no elements 🟪 .NET

InvalidOperationException: Sequence contains no elements / more than one element

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

Seen on: .NET

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?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.