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];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With