Introduction
Here, we going to see about how to use the aggregate function in LINQ
Knowledge required
- What is an aggregate function?
- Basics of C#
- Basics of LINQ.
Aggregate function
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.
Use of an aggregate function
The aggregation function is required to perform mathematical operations like Average, Aggregate, Count, Max, Min, and Sum on the numeric property of the elements in the collection and these methods are called as extension methods.
| Method | Description |
| Aggregate | Performs a custom aggregation operation on the values in the collection. |
| Average | Calculates the average of the numeric items in the collection. |
| Count | Counts the elements in a collection. |
| Max | Finds the largest value in the collection. |
| Min | Finds the smallest value in the collection |
| Sum | Calculate total(sum) value of the collection |
Aggregate
The aggregate method performs an accumulative operation. An aggregate extension method has the overload methods given below.
- public static TSource Aggregate<TSource>(this IEnumerable<TSource> source,
- Func<TSource, TSource, TSource> func);
- public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source,
- TAccumulate seed,
- Func<TAccumulate, TSource, TAccumulate> func);
- public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source,
- TAccumulate seed,
- Func<TAccumulate, TSource, TAccumulate> func,
- Func<TAccumulate, TResult> resultSelector);
Example (separating string by comma)
Create a new project as a console Application and write code given below. Separate the string by comma, using an aggregate method. By default, if we want to display the array in single line, it means that we will use split, foreach and we will use the concat but here the aggregate function is used just to accumulate.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace Linq {
- public class Program {
- public static void Main(string[] args) {
-
- string[] MySkills = {
- "C#.net",
- "Asp.net",
- "MVC",
- "Linq",
- "EntityFramework",
- "Swagger",
- "Web-Api",
- "OrcharCMS",
- "Jquery",
- "Sqlserver",
- "Docusign"
- };
- var commaSeperatedString = MySkills.Aggregate((s1, s2) => s1 + ", " + s2);
- Console.WriteLine("Aggregate : " + commaSeperatedString);
- }
- }
- }
Now, the output will be, as shown below.
How does it work?

S1=S1+","+S2;
work by below
1-S1="C#.net";
2-S1="C#.net"+","+"Asp.net";
3-S1="C#.net,Asp.net"+","+"MVC";
4-S1="C#.net,Asp.net,MVC"+","+"Linq";
5-S1="C#.net,Asp.net,MVC,Linq"+","+"EntityFramework";
6-S1="C#.net,Asp.net,MVC,Linq,EntityFramework"+","+"Swagger";
7-S1="C#.net,Asp.net,MVC,Linq,EntityFramework,Swagger"+","+"Web-Api";
8-S1="C#.net,Asp.net,MVC,Linq,EntityFramework,Swagger,Web-Api"+","+"OrcharCMS";
9-S1="C#.net,Asp.net,MVC,Linq,EntityFramework,Swagger,Web-Api,OrcharCMS"+","+"Jquery";
10-S1="C#.net,Asp.net,MVC,Linq,EntityFramework,Swagger,Web-Api,OrcharCMS,Jquery"+","+"Sqlserver";
11-S1="C#.net,Asp.net,MVC,Linq,EntityFramework,Swagger,Web-Api,OrcharCMS,Jquery,Sqlserver"+","+"Docusign";
Use the function inside aggregate
- int[] Addition = {
- 1,
- 2,
- 3,
- 4
- };
- int sum = Addition.Aggregate(func: Add);
- Console.WriteLine("Sum of Numbers:" + sum);
- private static int Add(int x, int y) {
- return x + y;
- }
How it works?
- private static int Add(int x, int y) {
- return x + y;
- step1: 1 + 2(x = 1, y = 2)
- step 2: 3 + 3(x = 3, y = 3)
- step 3: 6 + 4(x = 6, y = 4)
- finally it returns 10
- }
Average
It's used to find the average value from the respective collection
Example 1
- List<int> FindAverage = new List<int>() { 100, 120, 130 };
- var avg = FindAverage.Average();
- Console.WriteLine("Average Of Collection: {0}", avg);
Example 2
Add class.
- public class Employee {
- public int EmpID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public double Salary {
- get;
- set;
- }
- }
- Create List
- for above employee property
-
- List < Employee > Employee = new List < Employee > () {
- new Employee() {
- EmpID = 1, Name = "Gnanavel", Salary = 50000
- },
- new Employee() {
- EmpID = 2, Name = "Sekar", Salary = 40000
- },
- new Employee() {
- EmpID = 3, Name = "Subash", Salary = 20000
- },
- };
- var avgSalary = Employee.Average(s => s.Salary);
- Console.WriteLine("Average Salary of Employee: {0}", avgSalary);
Run the code and the ouput will be, as shown below.
Count
Count operator returns the number of the elements in the collection or the number of elements, which have satisfied the given condition.
Count() extension method overloads following two
- int Count<TSource>(); ---------------> how many elements are present in the respective collection.
- int Count<TSource>(Func<TSource, bool> predicate);-----------> how many elements are present's in respective collection with the satisfied condition.
int Count<TSource>()
- List < Employee > Employee = new List < Employee > () {
- new Employee() {
- EmpID = 1, Name = "Gnanavel", Salary = 50000
- },
- new Employee() {
- EmpID = 2, Name = "Sekar", Salary = 40000
- },
- new Employee() {
- EmpID = 3, Name = "Subash", Salary = 20000
- },
- };
Here, we going to find how many employees are present in an employee list.
- var CountValue = Employee.Count();
- Console.WriteLine("Count of Employee: {0}", CountValue);
int Count<TSource>(Func<TSource, bool> predicate)
Now, we going to see who has a salary more than 30000 for this.
- var SalaryMaxCount = Employee.Count(a => a.Salary >= 30000);
- Console.WriteLine("Count of Employee who has the salary more than 30,000: {0}", SalaryMaxCount);
Max
Find the max value from the collection, which is same as counting the max. It also overrides the same- The Max() extension method overloads following two.
- int Max<TSource>(); ---------------> Returns the maximum value from the respective collection.
- int Max<TSource>(Func<TSource, bool> predicate);-----------> Returns the maximum value from the respective collection with the satisfied condition.
int Max<TSource>(Func<TSource, bool> predicate);
- var maxSalary = Employee.Max(a => a.Salary);
- Console.WriteLine("Max salary: {0}", maxSalary);
int Max<TSource>();
- int[] Addition = { 1, 2, 3, 4 };
- var number = Addition.Max();
- Console.WriteLine("Max salary: {0}", number);
Min
Find the minimum value from the collection.
The Min() extension method overloads following two.
- int Min<TSource>(); ---------------> Returns the minimum value from the respective collection.
- int Min<TSource>(Func<TSource, bool> predicate);-----------> Returns the minimum value from the respective collection with the satisfied condition.
- int[] Addition = { 1, 2, 3, 4 };
- var Min = Addition.Min();
- Console.WriteLine("Min Number: {0}", Min);
int Min<TSource>(Func<TSource, bool> predicate)
- List < Employee > Employee = new List < Employee > () {
- new Employee() {
- EmpID = 1, Name = "Gnanavel", Salary = 50000
- },
- new Employee() {
- EmpID = 2, Name = "Sekar", Salary = 40000
- },
- new Employee() {
- EmpID = 3, Name = "Subash", Salary = 20000
- },
- };
- public class Employee {
- public int EmpID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public double Salary {
- get;
- set;
- }
- }
- var minSalary = Employee.Min(a => a.Salary);
- Console.WriteLine("Min salary: {0}", minSalary);
Sum
The Sum() method calculates the sum of the numeric items in the collection.
The Sum() extension method overloads following two.
- int Sum<TSource>(); ---------------> Returns the sum value from the respective collection.
- int Sum<TSource>(Func<TSource, bool> predicate);-----------> Returns the sum value from the respective collection with the satisfied condition.
int Sum<TSource>()
- int[] Addition = { 1, 2, 3, 4 };
- var Sum = Addition.Sum();
- Console.WriteLine("Sum of Number: {0}", Sum);
int Sum<TSource>(Func<TSource, bool> predicate)
- List < Employee > Employee = new List < Employee > ()
- {
- new Employee() {
- EmpID = 1, Name = "Gnanavel", Salary = 50000
- },
- new Employee() {
- EmpID = 2, Name = "Sekar", Salary = 40000
- },
- new Employee() {
- EmpID = 3, Name = "Subash", Salary = 20000
- },
- };
- public class Employee {
- public int EmpID {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public double Salary {
- get;
- set;
- }
- }
- var sumSalary = Employee.Sum(a => a.Salary);
- Console.WriteLine("Sum of salary: {0}", sumSalary);
Summary
In this article, we learned about how to use the aggregate functions with LINQ.
I hope this was helpful.
bilal javedPosted Sep 22, 2021, 1:38 PM
Performance overhead because string's are immutable
Nitin JainPosted Jul 17, 2019, 1:47 AM
Nice explanation...
MahmoudShehatta ShehattaPosted Dec 8, 2018, 8:44 AM
Thank you very much
Shameem AhmadPosted Jun 29, 2018, 6:57 AM
Nice article ..........
Saravanakumar SekaranPosted May 7, 2017, 3:56 AM
Wow simple superb article
Karthick KumarPosted May 3, 2017, 7:34 AM
Nice to Read sir...
Manav PandyaPosted Apr 12, 2017, 12:25 PM
Thanks fo sharing sir ....
Pankaj Kumar ChoudharyPosted Apr 12, 2017, 8:03 AM
Nice Read @Gnanavel Sekar liked the way of explanation....