加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:01:44 所属栏目:百科 来源:网络整理
导读:我有一个简单的Sum扩展: public static int? SumOrNullTSource(this IEnumerableTSource source,FuncTSource,int projection){ return source.Any() ? source.Sum(projection) : (int?)null;} 但它导致System.OverflowException:算术运算导致溢出. 我想要
我有一个简单的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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读