大数的 C# linq Sum() 扩展

标签 c# .net linq

我有一个简单的 Sum 扩展:

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

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

我想做的是这样的:

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

但是 Linq Sum 没有返回 ulong 和结果编译错误的重载。 有什么办法可以做到这一点?

最佳答案

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

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;
}

关于大数的 C# linq Sum() 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35458106/

相关文章:

c# - 如何将 XML 文件转换为 MessageContract 类的实例?

c# - MongoDB .NET 驱动程序查找全部 : How to write it better?

c# - ToolStripMenuItem 背景图像在鼠标悬停时消失(.net winforms)

c# - 不同的文本渲染方法不会产生我想要的

c# - 自动完成扩展程序未填充

.net - 使用 XLINQ 解析 XHTML 文件的库

c# - 连接和/或合并两个通用列表中的对象

c# - DateTime 到 BCD 表示法

c# - LINQ 到实体 : perform joins on many-to-many relationships (code first)

c# - 更改 gridview 单元格中特殊单词的前景色