C# Enumerable Aggregate(IEnumerable, TAccumulate, Func)

Description

Enumerable Aggregate(IEnumerable , TAccumulate, Func)Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.

Syntax

Enumerable.Aggregate(IEnumerable, TAccumulate, Func) has the following syntax.


public static TAccumulate Aggregate<TSource, TAccumulate>(
  this IEnumerable<TSource> source,
  TAccumulate seed,/*from   w  w w .  j  a  v a2  s. co  m*/
  Func<TAccumulate, TSource, TAccumulate> func
)

Parameters

Enumerable.Aggregate(IEnumerable, TAccumulate, Func) has the following parameters.

  • TSource - The type of the elements of source.
  • TAccumulate - The type of the accumulator value.
  • source - An IEnumerable to aggregate over.
  • seed - The initial accumulator value.
  • func - An accumulator function to be invoked on each element.

Returns

Enumerable.Aggregate(IEnumerable, TAccumulate, Func) method returns TAccumulate

Example

The following code example demonstrates how to use Aggregate to apply an accumulator function and use a seed value.


//w ww .j  a  va2 s . c om
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
    // Count the even numbers in the array, using a seed value of 0. 
    int numEven = ints.Aggregate(0, (total, next) =>
                                      next % 2 == 0 ? total + 1 : total);
    
    Console.WriteLine("The number of even integers is: {0}", numEven);

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable