22nd November 2023

Linq Product

Extension methods for calculating the product of a sequence of numbers.

public static int Product(this IEnumerable<int> x) => Product<int, int>(x);
public static long Product(this IEnumerable<long> x) => Product<long, long>(x);
public static float Product(this IEnumerable<float> x) => Product<float, float>(x);
public static double Product(this IEnumerable<double> x) => Product<double, double>(x);
public static decimal Product(this IEnumerable<decimal> x) => Product<decimal, decimal>(x);
private static TResult Product<TSource, TResult>(this IEnumerable<TSource> x)
    where TSource : struct, INumber<TSource>
    where TResult : struct, INumber<TResult>
    TResult result = TResult.One;
    foreach (var item in x)
            result *= TResult.CreateChecked(item);

    return result;