Aggregate
Learn custom accumulation with Aggregate.
Folding with Aggregate
Aggregate folds a sequence into a single value. It takes an accumulator and an update function; for each item it updates the accumulator and finally returns one value.
Example: numbers.Aggregate((acc, n) => acc + n) sums all numbers. On the first call acc is the first item and n the second. Through the loop acc carries the running total.
The seed value
Aggregate can also take a seed value: numbers.Aggregate(0, (acc, n) => acc + n). The seed is the initial accumulator; it does not mix with the first item. On an empty sequence the seed becomes the result.
Using a seed also lets the accumulator type differ from the item type. For example, join a string list with Aggregate("", (acc, s) => acc + s) into a single string.
Exercise Sum numbers with Aggregate
Compute the sum of the numbers list below with Aggregate and print it with Console.WriteLine.
Show example solution
Compute the sum with var sum = numbers.Aggregate((acc, n) => acc + n); then print with Console.WriteLine(sum);.
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var numbers = new List<int> { 1, 2, 3, 4 };
var sum = numbers.Aggregate((acc, n) => acc + n);
Console.WriteLine(sum);
}
}
Test yourself
-
What does Aggregate do?
- Filters the sequence
- Sorts the sequence
- Groups the sequence
- Folds the sequence to one value
Show answer
Folds the sequence to one value — Correct. Aggregate reduces a sequence to a single value with an accumulator.
-
Complete the Aggregate call
var sum = numbers.____((acc, n) => acc + n);Show answer
var sum = numbers.Aggregate((acc, n) => acc + n); -
Match the part to its role
- acc
- Accumulated value
- n
- Current item
- seed
- Starting value
- Aggregate
- Fold method