Azerty123 Azerty123 - 2 months ago 10
C# Question

Difference between several syntax of Sum() in Linq

What is the difference between these three calls of the method Sum in linq ?

decimal Sum1 = Shops.Sum(x => x.Amount);
decimal Sum2 = Shops.Select(x => x.Amount).Sum();
decimal Sum3 = Shops.Select(x => x).Sum(x => x.Amount);

Answer

There are subtle differences between each of the three above approaches, although with how you are currently calling each, they should result in the same amounts.

decimal Sum1 = Shops.Sum(x => x.Amount); uses the Func overload to identify the property being summed for the source collection and is used internally while iterating over the source.

decimal Sum2 = Shops.Select(x => x.Amount).Sum(); creates a new IEnumerable<T> projection, which is then passed into the .Sum() extension method and internally iterated and summed.

decimal Sum3 = Shops.Select(x => x).Sum(x => x.Amount); does nothing other than (potentially) create additional overhead and confusion, since it is identical to the first example, while allowing you to create a new projection along the way. It is essentially useless in this case.

Comments