dotnet/reactive · error · InvalidOperationException
Source sequence doesn't contain any elements.
Error message
Source sequence doesn't contain any elements.
What it means
ExtremaBy (the shared engine behind MaxBy, MaxByWithTies, MinBy, MinByWithTies) throws InvalidOperationException("Source sequence doesn't contain any elements.") when the sequence is empty, since a maximum/minimum key cannot be determined from zero elements. It surfaces at enumeration time, not call time.
Solutions
- Check sequence emptiness first (Any()) and handle the empty case explicitly
- Default the source to a single sentinel element, or use a seed-aware aggregation
- Wrap the call in try/catch for InvalidOperationException if emptiness is an expected runtime condition
- Fix the upstream filter/query that unexpectedly produced zero elements
Example fix
// before
var best = readings.MinBy(r => r.Value); // throws when empty
// after
var best = readings.Any()
? readings.MinBy(r => r.Value)
: null; // handle empty case explicitly Defensive patterns
Strategy: validation
Validate before calling
if (source is null) throw new ArgumentException("source is null", nameof(source));
if (!source.Any()) throw new InvalidOperationException("Sequence is empty; no extrema exist.");
var result = source.MaxBy(x => x.Key); Type guard
static bool IsNonEmpty<T>(IEnumerable<T>? s) => s is not null && s.Any();
Try / catch
try { best = source.MaxBy(x => x.Key); }
catch (InvalidOperationException ex) when (ex.Message.Contains("doesn't contain any elements")) { best = default; /* empty-case handling */ } Prevention
- Always check Any() before Min/Max-family operators on possibly empty data
- Document and enforce invariants that sequences must be non-empty
- Prefer Try-pattern or seed-based aggregation when empty input is legitimate
- Beware filters that can exclude every element
When it happens
Trigger: Calling any of MaxBy/MaxByWithTies/MinBy/MinByWithTies on an empty sequence: new int[0].MaxBy(x => x), a filtered query that matched nothing, or a stream that produced no items.
Common situations: Filter predicates that exclude everything, empty database tables or API results, collections expected to be non-empty by an invariant that was violated, first-run scenarios with no data yet.
Understand the failure class
Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.
Related errors
- Value cannot be null. (Parameter 'defaultSource')
- Value cannot be null. (Parameter 'source')
- Value cannot be null. (Parameter 'handler')
- Value cannot be null. (Parameter 'sources')
- Value cannot be null. (Parameter 'first')
AI-assisted analysis of dotnet/reactive@94b5d5ab91 (2026-09-15).
Data as JSON: /api/errors/f48d496b8bcc1f86.
Report an issue: GitHub.
Appendix: source
Thrown at Ix.NET/Source/System.Interactive/System/Linq/Operators/MaxByWithTies.cs:57
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (comparer == null)
throw new ArgumentNullException(nameof(comparer));
return ExtremaBy(source, keySelector, (key, minValue) => comparer.Compare(key, minValue));
}
private static IList<TSource> ExtremaBy<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> compare)
{
var result = new List<TSource>();
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
throw new InvalidOperationException("Source sequence doesn't contain any elements.");
var current = e.Current;
var resKey = keySelector(current);
result.Add(current);
while (e.MoveNext())
{
var cur = e.Current;
var key = keySelector(cur);
var cmp = compare(key, resKey);
if (cmp == 0)
{
result.Add(cur);
}
else if (cmp > 0)
{
result = [cur];View on GitHub (pinned to 94b5d5ab91)