typestar

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

  1. Sum, Average, Max and Min are the built-in folds.
  2. Count takes a predicate, so it filters and counts at once.
  3. Aggregate is the general fold: a seed, then combine left to right.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in LINQ, step 24 of 29 in Language basics.

← Previous Next →