Tip #009
Sum per group with AggregateBy
About this tip
AggregateBy groups and aggregates in one pass. No GroupBy + Select + Sum pipeline. Total weight per species without GroupBy().Select(Sum): .NET 9 AggregateBy groups and folds in one pass. It is available since .NET 9. The key line is var totals = pets.AggregateBy( in aggregateby.cs. Run it and the output reads Cat: 35, Dog: 259.
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
Pet[] pets = [ new(Species.Cat, 20), new(Species.Dog, 60), new(Species.Dog, 199), new(Species.Cat, 15),];
var totals = pets.AggregateBy( p => p.Species, 0, (sum, p) => sum + p.Weight);
foreach (var (species, weight) in totals) Console.WriteLine($"{species}: {weight}");
record Pet(Species Species, int Weight = 0);enum Species { Unknown, Cat, Dog }Output
$ dotnet run aggregateby.csCat: 35Dog: 259