Summary: in this tutorial, you’ll learn how to use the LINQ Aggregate()
method to perform a cumulative operation on a sequence.
Introduction to the LINQ Aggregate() method
The Aggregate()
method performs an operation on each element of a sequence, taking into account the result of the previous operation.
The Aggregate()
method starts by performing an operation on the first and second elements in the sequence and then carries the result forward. Then, it operates on the previous result and third element and carries the result forward.
The Aggregate()
method continues this process for all the remaining elements in the sequence. By the end, it combines all elements into a single result based on the operation performed at each step.
Here’s the syntax of the LINQ Aggregate()
method:
public static TSource Aggregate<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func
);
Code language: C# (cs)
In this syntax:
source
is the input sequence that has the type ofEnumerable<T>
.func
– a lambda expression that performs the operation on elements of the sequence.
The lambda expression takes two parameters:
- An accumulator that stores the result of the previous operation.
- The current value of the sequence.
The Aggregate()
method has an overload that accepts a seed value as follows:
public static TResult Aggregate<TSource,TAccumulate,TResult> (
IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate,TSource,TAccumulate> func
);
Code language: C# (cs)
In this syntax, the Aggregate()
method starts operating on the seed value with the first element and carries the result forward.
In case you want to transform the result, you can pass the resultSelector
function to the Aggregate()
method as follows:
public static TResult Aggregate<TSource,TAccumulate,TResult> (
IEnumerable<TSource> source,
TAccumulate seed,
Func<TAccumulate,TSource,TAccumulate> func,
Func<TAccumulate,TResult> resultSelector
);
Code language: C# (cs)
In this syntax, the resultSelector
transforms the final accumulator value into the result value.
LINQ Aggregate() method examples
Let’s take some examples of using the Aggregate()
method.
1) Using LINQ Aggregate() to calculate the sum of numbers
The following example demonstrates how to use the LINQ Aggregate()
method to calculate the sum of numbers of a list:
using static System.Console;
List<int> numbers = new() { 1, 2, 3, 4, 5 };
var step = 0;
int result = numbers.Aggregate((acc, current) =>
{
step++;
var sum = acc + current;
WriteLine($"Step {step}: acc={acc}, current={current}, sum={sum}");
return sum;
});
Code language: C# (cs)
Output:
Step 1: acc=1, current=2, sum=3
Step 2: acc=3, current=3, sum=6
Step 3: acc=6, current=4, sum=10
Step 4: acc=10, current=5, sum=15
Code language: C# (cs)
How it works.
First, define a list that has five numbers from 1 to 5:
List<int> numbers = new() { 1, 2, 3, 4, 5 };
Code language: C# (cs)
Second, define a variable that step and initialize it to zero:
var step = 0;
Code language: C# (cs)
Third, use the
method to perform a cumulative sum on the list. The lambda expression specified in the Aggregate()
method adds two numbers and returns the total. In addition, the lambda expression increments the step variable and writes the current value of acc, current, and sum to the console:Aggregate()
int result = numbers.Aggregate((acc, current) =>
{
step++;
var sum = acc + current;
WriteLine($"Step {step}: acc={acc}, current={current}, sum={sum}");
return sum;
});
Code language: C# (cs)
The
method starts with two elements of the numbers list and adds them up to return 3. The Aggregate()
method then takes 3 and adds it to the next number of the list (3) to get 6. The method repeats this process for the remaining elements. It returns the final result of 15.Aggregate()
The following program simplified the above program without writing the immediate results to the console:
using static System.Console;
List<int> numbers = new() { 1, 2, 3, 4, 5 };
int result = numbers.Aggregate((acc, current) => acc + current);
WriteLine(result);
Code language: C# (cs)
Notice that the purpose of this program is to help you understand how the Aggregate()
works. In practice, you should use the Sum()
function instead.
2) Using LINQ Aggregate() with a seed value
The following program demonstrates how to use the LINQ Aggregate()
method with a seed value to multiply all numbers in a list:
using static System.Console;
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var product = numbers.Aggregate(10, (acc, current) => acc * current);
WriteLine(product);
Code language: C# (cs)
Output:
1200
Code language: C# (cs)
In this example, we use the Aggregate()
method to multiply all numbers in the numbers list and return the result.
The Aggregate()
method starts with a seed value (10) and multiplies it by the first number of the numbers list, which results in 10.
The Aggregate()
method then multiplies the result (10) by the next element in the list (2) to get 20.
The Aggregate()
method repeats this process for the remaining numbers of the list until it has multiplied all the numbers together and returned the final result of 1200.
3) Using the LINQ Aggregate() method with a resultSelector function
The following example demonstrates how to use the LINQ Aggregate()
method with a result selector function:
List<string> words = new() {"simple", "is", "better", "than", "complex" };
string sentence = words.Aggregate(
"",
(acc, word) => { return acc != string.Empty ? acc + " " + word : word; },
acc => acc.ToUpper()
);
Console.WriteLine(sentence);
Code language: C# (cs)
Output:
SIMPLE IS BETTER THAN COMPLEX
Code language: C# (cs)
How it works.
First, define a list that has five strings.
Second, use the Aggregate()
method to concatenate all the strings in the list, separated by spaces, and convert the final accumulator into upper case.
The first lambda expression takes two parameters acc
and word that represents the accumulator and current element being processed respectively:
(acc, word) =>
{
return acc != string.Empty ? acc + " " + word : word;
}
Code language: C# (cs)
It concatenates the current string element with the accumulator, separated by a space if the accumulator is not empty, and returns the result as an accumulator.
The second lambda expression takes a single parameter acc
that represents the final accumulator value. It converts that value to uppercase and returns it as the final result of the Aggregate()
method:
acc => acc.ToUpper()
Code language: C# (cs)
Summary
- Use the
Aggregate()
method to perform an operation on the first and second elements and carry the result forward.