Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying all values in IEnumerable<int>

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

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....
like image 543
Jon Avatar asked Sep 14 '10 09:09

Jon


1 Answers

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.

like image 80
JaredPar Avatar answered Oct 15 '22 17:10

JaredPar