Aggregate
suggest changeAggregate applies an accumulator function over a sequence.
int[] intList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = intList.Aggregate((prevSum, current) => prevSum + current);
// sum = 55
- At the first step
prevSum = 1 - At the second
prevSum = prevSum(at the first step) + 2 - At the i-th step
prevSum = prevSum(at the (i-1) step) + i-th element of the array
string[] stringList = { "Hello", "World", "!" };
string joinedString = stringList.Aggregate((prev, current) => prev + " " + current);
// joinedString = "Hello World !"
A second overload of Aggregate also takes a seed parameter, which is the initial accumulator value. This can be used to calculate multiple results from a collection in one pass.
List<int> items = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
For the collection of items we want to calculate
- The total
.Count - The amount of even numbers
- Collect every fourth item
Using Aggregate it can be done like this:
var result = items.Aggregate(new { Total = 0, Even = 0, FourthItems = new List<int>() },
(accumulator,item) =>
new {
Total = accumulator.Total + 1,
Even = accumulator.Even + (item % 2 == 0 ? 1 : 0),
FourthItems = (accumulator.Total + 1)%4 == 0 ?
new List<int>(accumulator.FourthItems) { item } :
accumulator.FourthItems
});
// Result:
// Total = 12
// Even = 6
// FourthItems = [4, 8, 12]
Note that when the seed is an anonymous type, you must create a new object for each element because the properties are read-only. With a custom class you can assign the fields instead, and new is needed only for the initial seed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents