Aggregate with seed

In this chapter you will learn:

  1. How to use seeded aggregations

Seeded aggregations

You can omit the seed value when calling Aggregate. The first element becomes the implicit seed, and aggregation proceeds from the second element.

using System;//from   jav  a2  s  .c om
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3 };
        int x = numbers.Aggregate(0, (prod, n) => prod * n);  // 0*1*2*3 = 0
        int y = numbers.Aggregate((prod, n) => prod * n); //  1*2*3 = 6

        Console.WriteLine(x);

        Console.WriteLine(y);
    }
}

The output:

sum with seed

using System;//j av a2 s .com
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 2, 3, 4 };
        int sum = numbers.Aggregate(0, (total, n) => total + n);  // 9
        Console.WriteLine(sum);

    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Aggregate two string values
  2. Use Aggregate the reverse a string
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip