Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Enumerable.Sum Method doesn't support ulong type

Tags:

c#

lambda

linq

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:

  1. enter image description here
  2. enter image description here

    unless i do

ulong result = (ulong)listOfA.Sum(A => (long)A.Id)

Is there anyway to solve that without casting? Thanks!

like image 874
Z.Z. Avatar asked Feb 24 '16 21:02

Z.Z.


2 Answers

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;
}
like image 105
Philip Pittle Avatar answered Oct 20 '22 00:10

Philip Pittle


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.

like image 26
juharr Avatar answered Oct 20 '22 00:10

juharr