tags:

views:

115

answers:

1
+2  Q: 

Product with 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];
+10  A: 

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
Greg Beech
+1. recommend using int instead of var.
David B
Use of var is a personal/team decision. Personally I don't think type information is tremendously useful, and distracts you from the *purpose* of the code. I wrote about this here: http://gregbeech.com/blogs/tech/archive/2008/03/24/to-var-or-not-to-var-implicit-typing-is-the-question.aspx
Greg Beech