我有一个简单的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; }