Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate product with LINQ

Tags:

c#

linq

I am learning LINQ and have a very simple question that I think will help my understand the technology better. How can I find the product of an array of ints?

For example, what is the LINQ way to do:

int[] vals = { 1, 3, 5 };
return vals[0] * vals[1] * vals[2];
like image 846
Justin R. Avatar asked Oct 31 '08 01:10

Justin R.


1 Answers

This would work:

var product = vals.Aggregate(1, (acc, val) => acc * val);

You're starting with a seed of 1 and then the function is called for each of your values with two arguments, acc which is the current accumulated value, and val which is the value in the array; the function multiplies the current accumulated value by the value in the array and the result of that expression is passed as acc to the next function. i.e. the chain of function calls with the array you provided will be:

(1, 1) => 1
(1, 3) => 3
(3, 5) => 15
like image 157
Greg Beech Avatar answered Oct 13 '22 22:10

Greg Beech