C#linq Sum()扩展为大数字

use*_*945 3 .net c# linq

我有一个简单的Sum扩展:

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

但它会导致 System.OverflowException: Arithmetic operation resulted in an overflow.

我想要做的是这样的事情:

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

但Linq Sum没有超载,因此返回ulong和编译错误.任何方式使这项工作?

Yac*_*sad 5

您可以手动实现它.这是一个例子:

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;
}
Run Code Online (Sandbox Code Playgroud)