LINQ aggregation functions in bytes, shorts and unsigned values

How could you use LINQ aggregated functions (e.g. Sum, Average) for collections of bytes, shorts and unsigned values? Of course, I am a new C # programmer, but I can’t even figure out how to get something that compilation does not allow to get the correct result.

Here is a trivial example of what I'm trying to do:

short[] numbersArray = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; short sumArray = numbersArray.Sum(); 

or

 List<short> numbersList = new List<short> { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; short sumList = numbersList.Sum(); 

I cannot work any of these samples. If I change the data type to int, it works, but I can't get it to work for short messages, bytes, uints, etc.

What am I doing wrong?

+7
source share
4 answers

Enumerable.Sum<T>() is defined only for IEnumerable<T> , where T in

 double, double? int, int? decimal, decimal? long, long? float, float? 

This is because there is no addition operator * for short or any other primitive type ( short + short is int , for example).

You must say:

 short[] numbersArray = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int sumArray = numbersArray.Sum(x => (int)x); 

and less explicitly you can get away with

 short[] numbersArray = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int sumArray = numbersArray.Sum(x => x); 

In this case, you are now causing overload:

 int Enumerable.Sum<short>( this IEnumerable<short> source, Func<short, int> selector ) 

* : Here I mean the "operator" in the sense of the function F:(short x short) -> short .

+13
source

Enumerable.Sum accepts either int s, long s, single or double s.

You can specify numbers to match the parameter:

 short [] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int sum = numbers.Cast<int> ().Sum (); 

Alternatively, you can provide a Func<TSource, int> lambda that selects an int for you:

 short [] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; int sum = numbers.Sum (x => x); // lambda type is inferred as Func<short, int> 

I declare sum as int because it is really unsafe to think that the sum short is short itself .
This even affects the fact that you need to do explicit casting when adding short s:

 int sum = a + b; short shortSum = (short)(a + b); // you can use an explicit casting to get short 

So, if you are sure that you are not going to overflow, just enter the result :

 short shortSum = (short) numbers.Cast<int> ().Sum (); 
+5
source

The Sum extension method does not have an overload that accepts an IEnumerable<short> .

Instead, you can pass a lambda expression that implicitly converts short to int s:

 short sumList = (short)numbersList.Sum(i=>i); 
+2
source

This confused me, but I was able to make it work, like:

 List<short> li = new List<short> {1,2,3,4,5}; short l = (short)li.Sum(i => i); 
0
source

All Articles