Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Multiply an array elements with each other

Tags:

c#

c#-4.0

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.

like image 831
t_plusplus Avatar asked Dec 12 '22 07:12

t_plusplus


1 Answers

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);
}
like image 146
Heinzi Avatar answered Jan 04 '23 15:01

Heinzi