what is aggregate function in c# List
Aggregate Function
hi to all
what is aggregate function in c# List.How to use it can you please any one give some examples on this aggregate function
what is aggregate function in c# List
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Nilanka DharmadasaPosted Dec 23, 2009, 1:35 AM
Here is a small exmple which explains about aggregate function for list.
List
numlist.Add(1);
numlist.Add(2);
numlist.Add(3);
numlist.Add(4);
int mySum = numlist.Aggregate(1, (s, n) => s + n);
int myProduct = numlist.Aggregate((s, n) => s * n);
int myDifference = numlist.Aggregate((s, n) => s - n);
Console.WriteLine("Sum is: " + mySum.ToString());
Console.WriteLine("Difference is: " + myDifference.ToString());
Console.WriteLine("Product is: " + myProduct.ToString());
If you add this to a project and run, you will get following result.
Sum is: 11
Difference is: -8
Product is: 24
For aggregate method, the first parameter (optional parameter) is the seed. It means the initial value of the accumulator.
int mySum = numlist.Aggregate(1, (s, n) => s + n);
That's why this returned 11 instead of 10.
Second parameter is the function used. Here, the function is given as a lambda expression.
Lambda expression is somthing like this,
If you find my answer helpful, please tick 'Do you like this answer' checkbox.
srinivasPosted Dec 23, 2009, 4:24 AM