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);
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.
There is no difference in the final sum.
The difference is in the composure of the Expression Tree. These are all similar but do execute differently because the expression tree is being built differently.
LINQ works with deferred execution. In this case, it is deferred until the call to Sum
. Deferred execution in general works by enumerating an enumerable. The enumerable being built is different in each case.
Shops.Sum(x => x.Amount);
In this scenario, the Enumerable was already built, it is Shops
. The call to Sum
enumerates the Shops
enumerable and for each element adds the value of x.Amount
. This value is then returned.
Shops.Select(x => x.Amount).Sum();
In this scenario, the Enumerable being built is a "projection" (Select
). The projection is going to only take every Amount
from each Shop
element. Using Sum
on this enumerable iterates through each individual amount and adds it. The value is then returned.
Shops.Select(x => x).Sum(x => x.Amount);
This scenario may be compiled out. Select(x => x)
doesn't actually produce anything different. So this is more than likely the same as the first scenario.
.Select(x => x)
does nothing useful. So your question is basically what is the difference between the first and the second case. right?