For c# Enumerable.Sum<TSource> Method (IEnumerable<TSource>, Func<TSource, Int64>)
doesn't support ulong
type as the return type of the Mehtonf unless I cast ulong to long
.
public class A
{
public ulong id {get;set;}
}
publec Class B
{
public void SomeMethod(IList<A> listOfA)
{
ulong result = listofA.Sum(A => A.Id);
}
}
The compliler would throw two errors:
unless i do
ulong result = (ulong)listOfA.Sum(A => (long)A.Id)
Is there anyway to solve that without casting? Thanks!
You could write your own extension method to provide the overload for ulong
since it's not provided as part of the BCL:
public static ulong Sum<TSource>(
this IEnumerable<TSource> source, Func<TSource, ulong> summer)
{
ulong total = 0;
foreach(var item in source)
total += summer(item);
return total;
}
You could use Aggregate
instead.
ulong result = listOfULongs.Aggregate((a,c) => a + c);
Or in your specific case
ulong result = listOfA.Aggregate(0UL, (a,c) => a + c.Id);
You should also consider if you really should be using an unsigned value type in the first place.
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