System.InvalidOperationException: Sequence contains no elements
.NET · updated 2026-11-13
Thrown by LINQ's First, Last, Single, Min, Max and Average when the sequence is empty (and by Entity Framework's FirstAsync and SingleAsync when the query returns no rows). Single also throws "Sequence contains more than one element" when there are two or more.
Unhandled exception. System.InvalidOperationException: Sequence contains no elements at System.Linq.ThrowHelper.ThrowNoElementsException() at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) at Program.<Main>$(String[] args) in /app/Program.cs:line 2
Quick fix
Find the First/Single/Last/Max call in the first frame from your code. If an empty result is possible, switch to FirstOrDefault (or SingleOrDefault) and handle null, or check Any() first. If it should never be empty, the bug is upstream: the filter, the data or a missing seed row, so fail with a message that names what was missing.
- Skip the System.Linq frames: the first frame from your code is the call that hit an empty sequence.
- Decide whether empty is a normal result (no orders yet, no match for a filter).
- Normal: use FirstOrDefault/SingleOrDefault and handle null, or DefaultIfEmpty for Max/Min.
- Not normal: check the filter and the data, and throw a clear exception (or return 404) that names the missing record.
var latest = orders
.Where(o => o.Paid)
.OrderByDescending(o => o.At)
.FirstOrDefault();
if (latest is null)
return Results.NotFound("no paid orders yet");
// Max on a possibly empty sequence
var newest = orders.Select(o => (DateTime?)o.At).Max(); // null when emptyPaste this into Claude Code, Cursor or Codex in the project that throws it. The agent reads this guide in plain text and applies the fix that matches your stack.
Read https://runheed.com/errors/dotnet-sequence-contains-no-elements.md and fix this error in this project.Why it happens
The query has no matches for this user or tenant
It works with seeded development data and fails for a new account with no rows, or after a filter that excludes everything.
Max, Min or Average on an empty collection
These throw on an empty sequence of non-nullable values. Projecting to a nullable type returns null instead.
Single where duplicates exist
Single and SingleOrDefault throw "Sequence contains more than one element" when two rows match, often after a missing unique index.
A config or lookup table is missing a row
Code that reads settings.First(s => s.Key == "x") breaks in an environment where that row was never inserted.
Other fixes
- In Entity Framework, use FirstOrDefaultAsync and return 404 for a missing record from an API.
- Add a unique index where you use Single, so duplicates fail on insert instead of on read.
Same error, other wording
- System.InvalidOperationException: Sequence contains more than one element
- System.InvalidOperationException: Sequence contains no matching element
Let your coding agent catch the next one
Runheed records this error in production with the stack trace, the breadcrumbs before it and, when you set it, the agent session that shipped the code, and serves it to Claude Code, Cursor or any MCP client. With it connected, you can ask:
> Find the "Sequence contains no elements" errors in production, find the First/Single call in the latest one's stack, and decide with the data whether empty is valid (FirstOrDefault plus handling) or a bug upstream.
Setup for .NET and ASP.NET Core, then have your agent fix and resolve it.
Related errors
- System.NullReferenceException: Object reference not set to an instance of an object.
- java.lang.NullPointerException: Cannot invoke "String.toLowerCase()" because the return...
- KeyError: 'email'
More in Undefined, None and type errors
- panic: assignment to entry in nil mapGo
- TypeError: slugify(): Argument #1 ($title) must be of type string, null givenPHP
- panic: runtime error: invalid memory address or nil pointer dereferenceGo
- NoMethodError: undefined method 'email' for nilRuby
- TypeError: Cannot read properties of undefined (reading 'x')Node.js
- TypeError: Cannot destructure property 'id' of 'undefined' as it is undefined.Node.js
- TypeError: Cannot convert undefined or null to objectNode.js
- TypeError: items is not iterableNode.js
- TypeError: x is not a functionNode.js
- TypeError: Client is not a constructorNode.js
- ReferenceError: x is not definedNode.js
- ERR_INVALID_ARG_TYPE: The "path" argument must be of type string. Received undefinedNode.js
- TypeError: 'NoneType' object is not subscriptablePython
- AttributeError: 'NoneType' object has no attribute 'x'Python
- TypeError: 'NoneType' object is not iterablePython
- TypeError: unhashable type: 'list'Python
- AttributeError: 'dict' object has no attribute 'name'Python
- IndexError: list index out of rangePython
- TypeError: unsupported operand type(s) for +: 'int' and 'str'Python
- ValueError: invalid literal for int() with base 10: ''Python
- TypeError: __init__() got an unexpected keyword argument 'proxies'Python
- UnboundLocalError: cannot access local variable 'total' where it is not associated with a...Python
- RuntimeError: dictionary changed size during iterationPython
- ValueError: too many values to unpack (expected 2)Python
- TypeError: 'str' object is not callablePython
References: .NET API: Enumerable.First, .NET API: Enumerable.FirstOrDefault
Spotted a mistake? Email hello@greatwork.company. About Runheed.