C # Enumerable.Sum Method does not support ulong type

For C #, the Enumerable.Sum<TSource> Method (IEnumerable<TSource>, Func<TSource, Int64>) does not support the ulong type as the return type of Mehtonf unless I overlaid ulong on 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 compiler would have performed two errors:

  • enter image description here
  • enter image description here

    if i don't

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

Is there any way to solve this without casting? Thanks!

+5
source share
2 answers

Instead, you can use Aggregate .

 ulong result = listOfULongs.Aggregate((a,c) => a + c); 

Or in your particular case

 ulong result = listOfA.Aggregate(0UL, (a,c) => a + c.Id); 

You should also consider whether you should really use an unsigned value type.

+9
source

You can write your own extension method to provide overload for ulong , as it is not provided as part of 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; } 
+4
source

Source: https://habr.com/ru/post/1243797/


All Articles