views:

105

answers:

1

I have the following code and I am trying to work out how to multiply all values in my IEnumerable.

I thought there might by a Multiply method like there is with Sum. I guess I could do a foreach over each item but these days this seems tedious.

Any suggestions?

//1:2:6
string[] pkgratio = comboBox1.SelectedRow.Cells["PkgRatio"].Value.ToString().Split(':');
var ints = pkgratio.Select(x => int.Parse(x));         

int modvalue = ints....
+7  A: 

What you're looking for is the Aggregate function

int modValue = ints.Aggregate(1, (x,y) => x * y);

The Aggregate function takes in an initial accumulator value and then applies an operation to every value in the enumeration creating a new accumulator value. Here we start with 1 and then multiply ever value by the current value of the accumulator.

Note: In the case of an empty ints value this will return 1. This may or may not be correct for your situation.

JaredPar
Thanks. I just tried ints.Aggregate(1, (x,y) => x + y); and for 1,2,6 it add up to 10. I guess that is because it adds 1 to start with. Multiplying however will be ok??
Jon
@Jon: Yes. You can also omit the seed altogether and do `ints.Aggregate((x,y) => x * y)` but that will throw an exception if you feed it an empty sequence.
LukeH
I just tried and it throws an exception anyway even if the seed is there on a empty sequence
Jon