Difference between Sum and Aggregate in LINQ
You can essentially think of Sum as one particular type of Aggregate, but there are many other types.
Some examples of Aggregate might be to multiply every single value, or to add strings rather than numbers.
The reason that Sum exists in addition to Aggregate is simply that Sum is one of the more common types of Aggregate functions, so it was worthwhile to add an additional function for that case.
The Sum
operation is a specialization of Aggregate
. The Aggregate
operation is a way of collapsing a collection into a single value by applying a delegate that reduces a pair of values into a single value. Sum
is essentially calling Aggregate
with the +
function / operator
Aggregate
is much more flexible. It can be used on a wide number of types (to build strings for example). Sum
has a very specific purpose (to add numbers).
Sum method in Linq Operates only on numerical data type (int,float etc) where as Aggregate method can be operated on numerical data type as well as string data type.
string[] countries = { "Brazil", "Argentina", "England", "Spain"};
string result = countries.Aggregate((a, b) => a + ", " + b);
//result="Brazil,Argentina,England"
int[] Numbers = { 2, 3, 4 };
int aggregate= Numbers.Aggregate((a, b) => a * b);
//aggregate=24