C#: Multiply an array elements with each other
c#, c#-4.0
Solution
Another opportunity to show off the power of LINQ:
public static decimal MultiplyDecimals(params decimal[] decimals)
{
return decimals.Aggregate(1m, (p, d) => p * d);
}
This
- starts with an initial value of `1` (the `m` modifier statically types the constant as `decimal`) and then
- iteratively multiplies all the values.
EDIT: Here a variant that includes rounding. I've omitted it, because I don't think it's required (you don't have floating-point problems with `decimal`), but here it is for completeness:
public static decimal MultiplyDecimals(params decimal[] decimals)
{
return Math.Round(decimals.Aggregate(1m, (p, d) => p * d), 2);
}
Problem
I would like to be able to multiply all members of a given numeric array with each other. So for example for an array like: `[1,2,3,4]`, I would like to get the product of `1*2*3*4`. I have tried this but didn't work: ``` /// <summary> /// Multiplies numbers and returns the product as rounded to the nearest 2 decimal places. /// </summary> /// <param name="decimals"></param> /// <returns></returns> public static decimal MultiplyDecimals(params decimal[] decimals) { decimal product = 0; foreach (var @decimal in decimals) { product *= @decimal; } decimal roundProduct = Math.Round(product, 2); return roundProduct; } ``` I am sorry I know this must be simple! Thanks.