LINQ Aggregate Operators: What Lies Beyond Count and Sum in C#
LINQ offers a range of aggregate operators beyond the commonly used Count() and Sum(), including Average(), Min(), Max(), MinBy(), and MaxBy(). While Count and Sum handle empty sequences safely, operators like Average, Min, and Max throw InvalidOperationException on empty collections unless nullable overloads or DefaultIfEmpty() are used. Introduced in .NET 6, MinBy() and MaxBy() return the full element with the minimum or maximum value in a single pass, though they work only with in-memory LINQ and not EF Core. For database queries, the recommended equivalent is OrderBy() followed by FirstOrDefaultAsync(). The general-purpose Aggregate() operator serves as a flexible tool for building custom reductions, from running totals to string concatenation and tree structures.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in