LINQ and Aggregate function

LINQ also provides with itself important aggregate function. Aggregate function are function that are applied over a sequence like and return only one value like Average, count, sum, Maximum etc…
Below are some of the Aggregate functions provided with LINQ and example of their implementation.

Count

    int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };

    int uniqueFactors = primeFactorsOf300.Distinct().Count();

The below example provided count for only odd number.

    int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };

    int uniqueFactors = primeFactorsOf300.Distinct().Count(n => n%2 = 1);

 

Sum


    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };   

    double numSum = numbers.Sum();

 

Minimum

 

    int minNum = numbers.Min();


Maximum

 

    int maxNum = numbers.Max();

Average

 

    double averageNum = numbers.Average();

 

Aggregate

 

    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

    double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);

 

Vikram

No Comments