Spots

LINQ Aggregate Operators: Beyond Sum and Count

Everyone knows Count() and Sum(). But LINQ's aggregate family goes deeper — and the general-purpose Aggregate() operator can implement any of them, plus custom reductions you haven't imagined yet. Let's explore what's beyond the basics. These translate to SQL aggregates — executed in the database, not in memory. Efficient. What happens when the sequence is empty? Sum and Count handle emptiness gracefully. The others throw. The fix: use nullable overloads:

Fun fact: This null behavior matches SQL. SELECT

Fun fact: This null behavior matches SQL. SELECT AVG(Price) FROM Products WHERE 1=0 returns NULL, not zero. LINQ chose to throw exceptions because returning a misleading default (like 0 for average) could hide bugs. The nullable overloads give you SQL semantics when you want them. MinBy and MaxBy: The Element, Not the Value New in .NET 6, these return the element with the min/max value, not the value itself: MinBy/MaxBy are cleaner and more efficient. In-memory, it's one iteration instead of two. Note: these are LINQ to Objects only — EF Core doesn't translate them to SQL. Use OrderBy().First() for database: The General-Purpose Aggregate Aggregate() is the Swiss Army knife.

It takes: A function that combines accumulator +

It takes: A function that combines accumulator + element (Optionally) a result selector Build any aggregation you want: Real-World Aggregate Patterns Aggregate vs GroupBy for Summaries Need multiple aggregates by group? GroupBy with Select: This translates to efficient SQL with GROUP BY and aggregate functions. Count() returns int. If you have more than 2.1 billion items (rare, but possible): Database vs Memory Aggregation When aggregating on IQueryable, EF executes in the database: If you materialize first, aggregation happens in memory: For large datasets, database aggregation is dramatically faster. Always aggregate before .ToList() when possible. Aggregate in database — call Sum/Count on IQueryable, not after ToList() Watch for nulls — use nullable overloads for Min/Max/Average on possibly-empty sequences Need the element?

Use MinBy/MaxBy (.NET 6+) or OrderBy().First() Custom reduction?

Use MinBy/MaxBy (.NET 6+) or OrderBy().First() Custom reduction? Aggregate() can implement anything Per-group stats? GroupBy + aggregate functions

Next time, we'll tackle EF Core's raw SQL

Next time, we'll tackle EF Core's raw SQL escape hatch — FromSqlRaw, ExecuteSqlRaw, and when to break out of LINQ entirely. Hope to see you! For further actions, you may consider blocking this person and/or reporting abuse

News

LINQ Aggregate Operators: Beyond Sum and Count

Everyone knows Count() and Sum().

@spots #dev
Source: Dev.to
See more like this