Collection <T> .Sum (a => a.ushortProperty) for ulung

public class Foo { public ushort Weight { get; } } 
 public class Bar<T> : IEnumerable where T : Foo { private Collection<T> _contents; ... public ulong TotalWeight { get { return _contents.Sum(a => a.Weight); } } } 

I expect the amount to add more than the maximum ushort value.

I get an Intellisense error: "Ambiguous call", with a list of numeric types that does not include ushort or ulong. I'm not sure what he wants.

I also tried using Select (from this post ) as follows:

 _contents.Select(a => a.Weight).Sum() 

but Intellisense complains that it cannot resolve the Sum method and lists a group of candidates that also does not include ushort or ulong. Again, I'm not sure what he wants.

I apologize if this is really a newbie, I just don't understand what Intellisense is telling me.

+4
source share
1 answer

There is no Sum overload that applies to a ushort sequence or to a general sequence and projection onto a ushort . The simplest approach would be to simply apply to long :

 return _contents.Sum(a => (long) a.Weight); 

It will also alleviate the overflow problem. Please note that there is no overload with ulong . If you have enough ushort values ​​to overflow long , it will probably take some time to add them :)

+6
source

All Articles