Aggregate Function In LINQ

Introduction


Here, we going to see about how to use the aggregate function in LINQ

Knowledge required 
  1. What is an aggregate function?
  2. Basics of C#
  3. 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.
  1. public static TSource Aggregate<TSource>(this IEnumerable<TSource> source,  
  2. Func<TSource, TSource, TSource> func);  
  3. public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source,  
  4. TAccumulate seed,  
  5. Func<TAccumulate, TSource, TAccumulate> func);  
  6. public static TResult Aggregate<TSource, TAccumulate, TResult>(this IEnumerable<TSource> source,  
  7. TAccumulate seed,  
  8. Func<TAccumulate, TSource, TAccumulate> func,  
  9. 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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. namespace Linq {  
  6.     public class Program {  
  7.         public static void Main(string[] args) {  
  8.             //Aggregate  
  9.             string[] MySkills = {  
  10.                 "C#.net",  
  11.                 "Asp.net",  
  12.                 "MVC",  
  13.                 "Linq",  
  14.                 "EntityFramework",  
  15.                 "Swagger",  
  16.                 "Web-Api",  
  17.                 "OrcharCMS",  
  18.                 "Jquery",  
  19.                 "Sqlserver",  
  20.                 "Docusign"  
  21.             };  
  22.             var commaSeperatedString = MySkills.Aggregate((s1, s2) => s1 + ", " + s2);  
  23.             Console.WriteLine("Aggregate : " + commaSeperatedString);  
  24.         }  
  25.     }  
  26. }  
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
  1. int[] Addition = {  
  2.     1,  
  3.     2,  
  4.     3,  
  5.     4  
  6. };  
  7. int sum = Addition.Aggregate(func: Add);  
  8. Console.WriteLine("Sum of Numbers:" + sum);  
  9. private static int Add(int x, int y) {  
  10.     return x + y;  
  11. }  
How it works?
  1. private static int Add(int x, int y) {  
  2.     return x + y;  
  3.     step1: 1 + 2(x = 1, y = 2)  
  4.     step 2: 3 + 3(x = 3, y = 3)  
  5.     step 3: 6 + 4(x = 6, y = 4)  
  6.     finally it returns 10  
  7. }   
Average 

It's used to find the average value from the respective collection

Example 1
  1. List<int> FindAverage = new List<int>() { 100, 120, 130 };  
  2. var avg = FindAverage.Average();  
  3. Console.WriteLine("Average Of Collection: {0}", avg);  
 

Example 2

Add class.
  1. public class Employee {  
  2.     public int EmpID {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public double Salary {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. Create List  
  16. for above employee property  
  17. //Find the avg value from collection of modals  
  18. List < Employee > Employee = new List < Employee > () {  
  19.     new Employee() {  
  20.             EmpID = 1, Name = "Gnanavel", Salary = 50000  
  21.         },  
  22.         new Employee() {  
  23.             EmpID = 2, Name = "Sekar", Salary = 40000  
  24.         },  
  25.         new Employee() {  
  26.             EmpID = 3, Name = "Subash", Salary = 20000  
  27.         },  
  28. };  
  29. var avgSalary = Employee.Average(s => s.Salary);  
  30. 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>()
  1. List < Employee > Employee = new List < Employee > () {  
  2.     new Employee() {  
  3.             EmpID = 1, Name = "Gnanavel", Salary = 50000  
  4.         },  
  5.         new Employee() {  
  6.             EmpID = 2, Name = "Sekar", Salary = 40000  
  7.         },  
  8.         new Employee() {  
  9.             EmpID = 3, Name = "Subash", Salary = 20000  
  10.         },  
  11. };  
Here, we going to find how many employees are present in an employee list.
  1. var CountValue = Employee.Count();  
  2. 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.
  1. var SalaryMaxCount = Employee.Count(a => a.Salary >= 30000);  
  2. 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); 
  1. var maxSalary = Employee.Max(a => a.Salary);  
  2. Console.WriteLine("Max salary: {0}", maxSalary);  
 

int Max<TSource>();
  1. int[] Addition = { 1, 2, 3, 4 };  
  2. var number = Addition.Max();  
  3. 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 Min<TSource>() 
  1. int[] Addition = { 1, 2, 3, 4 };  
  2. var Min = Addition.Min();  
  3. Console.WriteLine("Min Number: {0}", Min);  


int Min<TSource>(Func<TSource, bool> predicate)

  1. List < Employee > Employee = new List < Employee > () {  
  2.     new Employee() {  
  3.             EmpID = 1, Name = "Gnanavel", Salary = 50000  
  4.         },  
  5.         new Employee() {  
  6.             EmpID = 2, Name = "Sekar", Salary = 40000  
  7.         },  
  8.         new Employee() {  
  9.             EmpID = 3, Name = "Subash", Salary = 20000  
  10.         },  
  11. };  
  12. public class Employee {  
  13.     public int EmpID {  
  14.         get;  
  15.         set;  
  16.     }  
  17.     public string Name {  
  18.         get;  
  19.         set;  
  20.     }  
  21.     public double Salary {  
  22.         get;  
  23.         set;  
  24.     }  
  25. }  
  26. var minSalary = Employee.Min(a => a.Salary);  
  27. 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>()
  1. int[] Addition = { 1, 2, 3, 4 };  
  2. var Sum = Addition.Sum();  
  3. Console.WriteLine("Sum of Number: {0}", Sum);  
 

int Sum<TSource>(Func<TSource, bool> predicate)
  1. List < Employee > Employee = new List < Employee > ()  
  2. {  
  3.     new Employee() {  
  4.             EmpID = 1, Name = "Gnanavel", Salary = 50000  
  5.         },  
  6.         new Employee() {  
  7.             EmpID = 2, Name = "Sekar", Salary = 40000  
  8.         },  
  9.         new Employee() {  
  10.             EmpID = 3, Name = "Subash", Salary = 20000  
  11.         },  
  12. };  
  13. public class Employee {  
  14.     public int EmpID {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Name {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public double Salary {  
  23.         get;  
  24.         set;  
  25.     }  
  26. }  
  27. var sumSalary = Employee.Sum(a => a.Salary);  
  28. 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.


Similar Articles