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