pabloflinstone pabloflinstone - 20 days ago 7
C# Question

What is the equivalent of IEnumerable.Sum() to Calculate the product of a list?

Im trying to calculate the product of values in a list of strings (Created by a RegEx.Split). I can use

Sum
this way:

var s = new[] { 2, 3, 4 }.Sum();
// s should be 9


What I want is to have an equivalent was to calculate the product instead of the sum like this:

var s = new[] { 2, 3, 4 }.Mul();
// s should be 24

Answer

The sum method is included as an extensions method to IEnumerable in the .net framework. There is no equivalent function to calculate the product of an IEnumerable, but you can write your own:

public static class MultiplyExtension
{
    /// <summary>
    /// Note that product of empty list is 0.
    /// </summary>
    public static float Mul<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector)
    {
        // caluclate the product of all the elements
        float result = 1;
        foreach (var element in Enumerable.Select(source, selector))
        {
            result *= element;
        }
        return result;
    }
}