Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq Sum() extension for large numbers

Tags:

c#

.net

linq

I have a simple Sum extension:

public static int? SumOrNull<TSource>(this IEnumerable<TSource> source, Func<TSource, int> projection)
{
    return source.Any()
        ? source.Sum(projection)
        : (int?)null;
}

But it causes System.OverflowException: Arithmetic operation resulted in an overflow.

What I'm trying to do is something like this:

public static ulong? SumOrNull<TSource>(this IEnumerable<TSource> source, Func<TSource, int> projection)
{
    return source.Any()
        ? source.Sum(projection)
        : (ulong?)null;
}

But Linq Sum does not have overload that returns ulong and compilation error as a result. Any way to make that work?

like image 690
user1016945 Avatar asked Dec 05 '25 10:12

user1016945


1 Answers

You can implement it manually. Here is an example:

public static ulong? SumOrNull<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, int> projection)
{
    bool any = false;

    ulong sum = 0;

    foreach (var item in source)
    {
        any = true;

        //As commented by CodesInChaos,
        //we use the checked keyword to make sure that
        //we throw an exception if there are any negative numbers
        sum = sum + (ulong)checked((uint)projection(item));
    }

    if (!any)
        return null;

    return sum;
}
like image 154
Yacoub Massad Avatar answered Dec 07 '25 22:12

Yacoub Massad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!