{"record":{"id":"f48d496b8bcc1f86","repo":"dotnet/reactive","slug":"source-sequence-doesn-t-contain-any-elements","errorCode":null,"errorMessage":"Source sequence doesn't contain any elements.","messagePattern":"Source sequence doesn't contain any elements\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"Ix.NET/Source/System.Interactive/System/Linq/Operators/MaxByWithTies.cs","lineNumber":57,"sourceCode":"        {\n            if (source == null)\n                throw new ArgumentNullException(nameof(source));\n            if (keySelector == null)\n                throw new ArgumentNullException(nameof(keySelector));\n            if (comparer == null)\n                throw new ArgumentNullException(nameof(comparer));\n\n            return ExtremaBy(source, keySelector, (key, minValue) => comparer.Compare(key, minValue));\n        }\n\n        private static IList<TSource> ExtremaBy<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> compare)\n        {\n            var result = new List<TSource>();\n\n            using (var e = source.GetEnumerator())\n            {\n                if (!e.MoveNext())\n                    throw new InvalidOperationException(\"Source sequence doesn't contain any elements.\");\n\n                var current = e.Current;\n                var resKey = keySelector(current);\n                result.Add(current);\n\n                while (e.MoveNext())\n                {\n                    var cur = e.Current;\n                    var key = keySelector(cur);\n\n                    var cmp = compare(key, resKey);\n                    if (cmp == 0)\n                    {\n                        result.Add(cur);\n                    }\n                    else if (cmp > 0)\n                    {\n                        result = [cur];","sourceCodeStart":39,"sourceCodeEnd":75,"githubUrl":"https://github.com/dotnet/reactive/blob/94b5d5ab912789f5abe9a72138a25bbd716fe59c/Ix.NET/Source/System.Interactive/System/Linq/Operators/MaxByWithTies.cs#L39-L75","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"// before\nvar best = readings.MinBy(r => r.Value); // throws when empty\n// after\nvar best = readings.Any()\n    ? readings.MinBy(r => r.Value)\n    : null; // handle empty case explicitly","handlingStrategy":"validation","validationCode":"if (source is null) throw new ArgumentException(\"source is null\", nameof(source));\nif (!source.Any()) throw new InvalidOperationException(\"Sequence is empty; no extrema exist.\");\nvar result = source.MaxBy(x => x.Key);","typeGuard":"static bool IsNonEmpty<T>(IEnumerable<T>? s) => s is not null && s.Any();","tryCatchPattern":"try { best = source.MaxBy(x => x.Key); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"doesn't contain any elements\")) { best = default; /* empty-case handling */ }","preventionTips":["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"],"tags":["csharp","empty-sequence","invalidoperationexception","linq"],"backgroundTag":"empty-result-set","analyzedSha":"94b5d5ab912789f5abe9a72138a25bbd716fe59c","analyzedAt":"2026-09-15T02:26:24.759Z","contentChangedAt":"2026-09-15T02:26:24.759Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}