Aggregate

suggest change

Aggregate 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
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

  1. The total .Count
  2. The amount of even numbers
  3. 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents