LINQ and Aggregate function
Posted
by vik20000in
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by vik20000in
Published on Fri, 30 Apr 2010 08:47:00 GMT
Indexed on
2010/04/30
9:17 UTC
Read the original article
Hit count: 515
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
© ASP.net Weblogs or respective owner