Urgent.News

What's breaking now, across thousands of outlets.

Tech

LINQ Aggregate Operators: Beyond Sum and Count

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. The Usual Suspects var products = dbContext . Products ; var count = products . Count (); // Number of items var…

LINQ aggregate operators extend beyond the basic Sum and Count functions, offering a powerful tool for custom reductions. The Aggregate() operator can implement any aggregation, including custom ones.

Basic LINQ aggregate functions like Count(), Sum(), Average(), Min(), and Max() translate to SQL aggregates, executing efficiently in the database. However, when the sequence is empty, Sum() and Count() handle this gracefully by returning 0, while the others throw an InvalidOperationException.

To avoid this exception, nullable overloads can be used, returning null instead of an error. This matches SQL behavior, where SELECT AVG(Price) FROM Products WHERE 1=0 returns NULL. The nullable overloads provide SQL-like semantics when needed.

New in .NET 6 are MinBy and MaxBy methods, which return the element with the minimum or maximum value, respectively, rather than the value itself. This is more efficient as it requires only one iteration. However, these methods are specific to LINQ to Objects and not supported by EF Core.

The Aggregate() function is a versatile tool that can build any aggregation, taking a seed value, a combining function, and optionally a result selector. For example, it can manually implement a sum or product calculation.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

Flash Loan Attack Vector Analysis: Portal

Flash Loan Attack Vector Analysis: Portal Target Protocol : Portal (TVL: $1805.6M) Flash Loan Attack Vector Analysis – Portal Protocol: Portal (TVL ≈ $1.805 B across Ethereum L1 & L2) Prepared by…

More from Tuesday 29 September →