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

我有一个简单的Sum扩展:

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

但它导致System.OverflowException:算术运算导致溢出.

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

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

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

解决方法

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

public static ulong? SumOrNull<TSource>(
    this IEnumerable<TSource> source,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;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...