Search code examples
c#linqlambda

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


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!


Solution

  • 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.