In C#, the Aggregate
method is part of LINQ.
It allows to perform an operation on all elements of a collection to accumulate a result.
It applies a specified function to each element in the collection, along with an accumulator value, and returns a single aggregated result.
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int product = numbers.Aggregate((accumulator, currentNumber) => accumulator * currentNumber);
Console.WriteLine("Product: " + product);
}
}
In this example, the accumulator
represents the accumulated result, and currentNumber
represents the current number in the iteration.
The Aggregate
method starts with the first element of the list as the initial accumulator
value and then applies the lambda expression to each subsequent element in the list, accumulating the product.
Another example:
public string BookTitlesAfter2015Concatenated()
{
return booksCollection
.Where(p => p.PublishedDate.Year > 2015)
.Aggregate("", (BookTitles, next) =>
{
if (BookTitles != string.Empty)
BookTitles += " - " + next.Title;
else
BookTitles += next.Title;
return BookTitles;
});
}
Basically, concatenates iteratively and stores the string (string in this case) into the variable BookTitles.