Applying aggregate function in LINQ

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


Share this post   Email it

Feedback

Posted on 7/31/2010 11:46:53 PM

nice!

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia