Aggregates
Count, Sum, Min, Max, Average
An aggregate turns a sequence into one value. The five numeric ones are methods on any sequence of a numeric type, and each walks the source once:
var values = new[] { 4, 8, 15, 16, 23, 42 };
Console.WriteLine($"count {values.Count()} sum {values.Sum()}");
Console.WriteLine($"min {values.Min()} max {values.Max()}");
Console.WriteLine($"average {values.Average():F3}");
Console.WriteLine($"empty average {Array.Empty<int>().DefaultIfEmpty(0).Average()}");
dotnet run
count 6 sum 108
min 4 max 42
average 18.000
empty average 0
Six values add up to 108 and average 18 exactly, so the F3 format shows three zeros. The last line is the careful case: Average() on an empty sequence throws InvalidOperationException, so DefaultIfEmpty(0) puts one zero in front of it and the average becomes that zero. Sum of an empty sequence needs no such help and returns 0.
Any and All
Any and All answer a question with a bool, and both stop as soon as the answer is known: Any after the first match, All after the first counter-example. The empty sequence is the case a reader has to think about:
var values = new[] { 4, 8, 15, 16, 23, 42 };
var empty = Array.Empty<int>();
Console.WriteLine($"any > 40: {values.Any(v => v > 40)}");
Console.WriteLine($"all > 0: {values.All(v => v > 0)}");
Console.WriteLine($"all > 10: {values.All(v => v > 10)}");
Console.WriteLine($"any in empty: {empty.Any()}");
Console.WriteLine($"all in empty: {empty.All(v => v > 10)}");
dotnet run
any > 40: True
all > 0: True
all > 10: False
any in empty: False
all in empty: True
42 is above 40, and every value is above zero. 4 is not above 10, so All is false. The two empty lines are the ones to remember: no item is above 40 when there are no items, so Any is false, and every item satisfies any condition when there are no items, so All is true. The second is not a bug: it is the standard reading of "all", the same way that an empty sum is zero.
Aggregate
Aggregate is the general form of the others: a seed and a function that takes the running value and the next item. Sum is Aggregate(0, (a, b) => a + b) written for you.
var values = new[] { 4, 8, 15, 16, 23, 42 };
var csv = values
.Select(v => v.ToString())
.Aggregate((left, right) => $"{left}-{right}");
var total = values.Aggregate(0, (sum, value) => sum + value);
var withSeed = values.Aggregate(1000, (sum, value) => sum + value);
Console.WriteLine(csv);
Console.WriteLine($"total {total} with seed {withSeed}");
Console.WriteLine($"count {values.Aggregate(0, (n, _) => n + 1)}");
dotnet run
4-8-15-16-23-42
total 108 with seed 1108
count 6
The two-argument overload has no seed: it takes the first item as the running value and folds the rest into it. The three-argument overload starts from the seed, which is why 1000 plus 108 is 1108. The last line counts with Aggregate instead of Count() to show that the accumulator can be any value, not only one of the item type.
The aggregate that does not compile
The seedless overload infers its accumulator type from the items, so the lambda must return that type. This program tries to fold integers into a string without projecting them first:
var values = new[] { 4, 8, 15, 16, 23, 42 };
var csv = values.Aggregate((left, right) => $"{left}-{right}");
var total = values.Aggregate(0, (sum, value) => sum + value);
var withSeed = values.Aggregate(1000, (sum, value) => sum + value);
Console.WriteLine(csv);
Console.WriteLine($"total {total} with seed {withSeed}");
Console.WriteLine($"count {values.Aggregate(0, (n, _) => n + 1)}");
dotnet build
Program.cs(3,45): error CS0029: Cannot implicitly convert type 'string' to 'int'
Program.cs(3,45): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
Build FAILED.
Program.cs(3,45): error CS0029: Cannot implicitly convert type 'string' to 'int'
Program.cs(3,45): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
0 Warning(s)
2 Error(s)
Time Elapsed 00:00:05.17
The first error is the real one: the accumulator of int items returns an int, and the interpolation returns a string. The second is the compiler explaining the same mismatch from the side of the delegate. The fix is the projection that the working program above carries: Select(v => v.ToString()) first, then fold strings. Reading the first error and ignoring the rest is the habit that saves time here, because the rest is usually a consequence.
Exercises
- Print the average of an empty array without DefaultIfEmpty and read the exception.
- Write Min and Max by hand with Aggregate and check them against the built-in ones.
- Use Any to check whether a list of strings contains an empty one, and All to check that none is.
- Compute the product of the values with Aggregate(1, ...) and explain why a seed of 1 is the right one.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Average()on an empty sequence of int do?Answer
Throws InvalidOperationException
An average needs at least one item, so the method throws rather than invent a value.
-
What does
Allreturn for an empty sequence?Answer
True
With no counter-example, the condition holds for every item, so All is true.
-
What does this program print?
var v = new[] { 2, 3, 4 }; Console.WriteLine(v.Sum());Answer
9
Sum adds the three values: 2 + 3 + 4 is 9.
-
What is the difference between the two overloads of Aggregate?
Answer
One starts from the first item, the other from a seed
The seedless form uses the first item as the accumulator; the form with a seed starts from the value given.
-
Why does
values.Aggregate((a, b) => $"{a}-{b}")not compile?Answer
The accumulator must return the item type, here int
The seedless accumulator is Func<int, int, int>, and the interpolation produces a string.
-
Which aggregate stops at the first matching item?
Answer
Any
Any only needs one match, so it returns as soon as it finds it.
-
What does this program print?
var v = new[] { 5, 9, 2 }; Console.WriteLine(v.Min() + v.Max());Answer
11
The minimum is 2 and the maximum is 9, and their sum is 11.
-
What does
DefaultIfEmpty(0).Average()protect against?Answer
The exception Average throws on an empty sequence
DefaultIfEmpty supplies one item, so Average has something to divide by.
-
What is Sum of an empty sequence of decimals?
Answer
0
Sum over an empty numeric sequence returns the zero of the type.
-
Which of these walks the source once?
Answer
Sum()
Each aggregate is one walk; two aggregates are two walks unless the query is materialised first.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev