I have a simple Sum extension:
public static int? SumOrNull<TSource>(this IEnumerable<TSource> source, Func<TSource, int> projection)
{
return source.Any()
? source.Sum(projection)
: (int?)null;
}
But it causes System.OverflowException: Arithmetic operation resulted in an overflow.
What I'm trying to do is something like this:
public static ulong? SumOrNull<TSource>(this IEnumerable<TSource> source, Func<TSource, int> projection)
{
return source.Any()
? source.Sum(projection)
: (ulong?)null;
}
But Linq Sum does not have overload that returns ulong and compilation error as a result. Any way to make that work?
You can implement it manually. Here is an example:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With