Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Sum and Aggregate in LINQ

Tags:

c#

linq

What is the diffrence between the two functions: Sum / Aggregate?

like image 321
Elad Benda Avatar asked Feb 13 '12 20:02

Elad Benda


People also ask

What does aggregate do in Linq?

In LINQ, aggregation functions are those functions which are used to calculate a single value from the collection of the values.

What does the aggregate () method do C#?

An aggregate function is a function and is required to group together the values of the multiple rows as the input and returns the output as single value of greater significance. An aggregate function returns a single value.

Is sum an aggregation?

Various types of SQL aggregate functions are: Count() Sum() Avg()

How do you sum in Linq?

In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.


1 Answers

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
like image 188
Zeewon Maharjan Avatar answered Sep 21 '22 06:09

Zeewon Maharjan