Question

Hello it is possible to change Sum return type without changing type of enumerable?

string func(int a)
{
    return (from el in Enumerable.Range(0, a >> 1) select el << 1).Sum().ToString();
}

I want to get Sum() as int64 of

(from el in Enumerable.Range(0, a >> 1) select el << 1)
Was it helpful?

Solution

Sum always uses the type of the enumerable (or the result type of the mapping function) and has overloads for the different numeric types. In this case, simply alter the Select as so to get the values to be added as longs1 (and the result to be a long).

// uses: long Enumerable.Sum(IEnumerable<long> t)
(.. select (long)(el << 1)).Sum()

Or, use the overload that takes in a mapping function.

// uses: long Enumerable.Sum(IEnumerable<T> t, Func<T,long> f)
(.. select el << 1).Sum(i => (long)i)

To only get the result as a different type (without affecting the type used for the summation), simply perform the cast/conversion at the end. Because this only changes the type after the summation it affects precision and range/overflow during the Sum function differently than the first two methods shown.

(long)(.. select el << 1).Sum()

1 In C#, long is System.Int64.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top