Aggregates in C#
Collapse a sequence to one number, five different ways.
var readings = new[] { 3.2, 4.8, 2.9, 5.1, 4.0 };
Console.WriteLine(readings.Sum());
Console.WriteLine(readings.Average());
Console.WriteLine(readings.Max() - readings.Min());
Console.WriteLine(readings.Count(r => r > 4));
// Aggregate folds left to right through an accumulator
var product = readings.Aggregate(1.0, (acc, r) => acc * r);
Console.WriteLine($"{product:F1}");
How it works
Sum,Average,MaxandMinare the built-in folds.Counttakes a predicate, so it filters and counts at once.Aggregateis the general fold: a seed, then combine left to right.
Keywords and builtins used here
newvar
The run, in numbers
- Lines
- 10
- Characters to type
- 376
- Tokens
- 101
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 64 seconds.
Step 3 of 3 in LINQ, step 24 of 29 in Language basics.