How To Use Aggregation Operations With Database Using LINQ

Introduction

In this article, I will demonstrate how we can use Sum, Min, Max Count, Average, LongCount, and Aggregate operator of Language-Integrated Query (LINQ). Sum, Min, Max Count, Average, LongCount, Aggregate operators are part of the aggregation operation in LINQ. An aggregation operation computes a single value from a collection of values. An example of an aggregation operation is - calculating the average daily temperature from a month's worth of daily temperature values.

 

  • Sum - Calculates the sum of the values in a collection.
  • Min - Determines the minimum value in a collection.
  • Max - Determines the maximum value in a collection.
  • Count - Counts the elements in a collection, optionally only those elements that satisfy a predicate function.
  • Average - Calculates the average value of a collection of values.
  • LongCount - Counts the elements in a large collection, optionally only those elements that satisfy a predicate function.
  • Aggregate - Performs a custom aggregation operation on the values of a collection.

 

Step 1

Open SQL Server 2014 and create a table named Products. Insert some records in it.

  1. CREATE TABLE [dbo].[Products](  
  2.     [Product_Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Product_Name] [nvarchar](50) NULL,  
  4.     [Quantity] [int] NULL,  
  5.     [Price] [money] NULL,  
  6.  CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [Product_Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
  10. ) ON [PRIMARY]  
  11.   
  12. GO  

Step 2

Open Visual Studio 2015 and create a new console application with a meaningful name.

Step 3

Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.

Screenshot for adding Entity framework

LINQ

 

After clicking on the new item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name DBModels (this name is not mandatory; you can give any name) and click on Add.

Screenshot for adding Entity framework 2

LINQ
 
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click Next.

Screenshot for adding Entity framework 3

LINQ
 
After clicking on Next, a window will appear. Choose New Connection. Another window will appear. Add your server name; if it is local then enter dot (.). Choose your database and click on OK.

Screenshot for adding Entity framework 4

LINQ
 
The connection will be added. If you wish, you can save the connection as you want. You can change the name of your connection. It will save the connection in web config. Now, click on Next.

Screenshot for adding Entity framework 5

LINQ
 
After clicking on NEXT, another window will appear. Choose database table name as shown in the below screenshot then click on Finish.

Screenshot for adding Entity framework 6

LINQ

Screenshot for adding Entity framework 7

LINQ
 
Entity framework will be added and a respective class gets generated under the Models folder.

Screenshot for adding Entity framework 8

LINQ

The following class will be added.

  1. namespace AggregationOperations_Demo  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Product  
  7.     {  
  8.         public int Product_Id { get; set; }  
  9.         public string Product_Name { get; set; }  
  10.         public Nullable<int> Quantity { get; set; }  
  11.         public Nullable<decimal> Price { get; set; }  
  12.     }  
  13. }  

Step 4

Write a program to call the database class.

Example of Sum operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace AggregationOperations_Demo  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             using (DBModel db=new DBModel ())  
  12.             {  
  13.                 List<Product>listProduct=db.Products.ToList<Product>();  
  14.   
  15.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  16.   
  17.                 foreach (var product in listProduct)  
  18.                 {  
  19.                     Console.WriteLine(product.Product_Id+"\t"+product.Product_Name+ "\t\t" + product.Quantity+ "\t" + product.Price);  
  20.                 }  
  21.   
  22.                 Console.WriteLine();  
  23.   
  24.                 Console.WriteLine("TOTAL PRODUCTS \n");  
  25.   
  26.                 int result = listProduct.Sum(q=>q.Quantity??0);  
  27.   
  28.                 Console.WriteLine("Total Product:\t"+ result);  
  29.    Console.ReadLine();  
  30.   
  31.             }  
  32.         }  
  33.     }  
  34. }  
Output

LINQ

Example of Min Operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace AggregationOperations_Demo  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             using (DBModel db=new DBModel ())  
  12.             {  
  13.                 List<Product>listProduct=db.Products.ToList<Product>();  
  14.   
  15.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  16.   
  17.                 foreach (var product in listProduct)  
  18.                 {  
  19.                     Console.WriteLine(product.Product_Id+"\t"+product.Product_Name+ "\t\t" + product.Quantity+ "\t" + product.Price);  
  20.                 }  
  21.   
  22.                 Console.WriteLine();  
  23.   
  24.                 Console.WriteLine("PRODUCTS LIST\n");  
  25.   
  26.                 int result = listProduct.Min(q=>q.Quantity??0);  
  27.   
  28.                 Console.WriteLine("Lowest Product Quantity:\t"+ result);  
  29.      Console.ReadLine();  
  30.             }  
  31.         }  
  32.     }  
  33. }  
Output
 
LINQ

Example of Max Operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace AggregationOperations_Demo  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             using (DBModel db=new DBModel ())  
  12.             {  
  13.                 List<Product>listProduct=db.Products.ToList<Product>();  
  14.   
  15.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  16.   
  17.                 foreach (var product in listProduct)  
  18.                 {  
  19.                     Console.WriteLine(product.Product_Id+"\t"+product.Product_Name+ "\t\t" + product.Quantity+ "\t" + product.Price);  
  20.                 }  
  21.   
  22.                 Console.WriteLine();  
  23.   
  24.                 Console.WriteLine("PRODUCTS LIST \n");  
  25.   
  26.                 int result = listProduct.Max(q=>q.Quantity??0);  
  27.   
  28.                 Console.WriteLine("Highest Product Quantity:\t" + result);  
  29.      Console.ReadLine();  
  30.   
  31.             }  
  32.         }  
  33.     }  
  34. }  
Output 
 
LINQ

Example of Average Operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace AggregationOperations_Demo  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             using (DBModel db=new DBModel ())  
  12.             {  
  13.                 List<Product>listProduct=db.Products.ToList<Product>();  
  14.   
  15.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  16.   
  17.                 foreach (var product in listProduct)  
  18.                 {  
  19.                     Console.WriteLine(product.Product_Id+"\t"+product.Product_Name+ "\t\t" + product.Quantity+ "\t" + product.Price);  
  20.                 }  
  21.   
  22.                 Console.WriteLine();  
  23.   
  24.                 Console.WriteLine("PRODUCTS LIST\n");  
  25.   
  26.                 decimal result = listProduct.Average(q => q.Price??0);  
  27.   
  28.                 Console.WriteLine("Average Product Price:\t"+ result);  
  29.      Console.ReadLine();  
  30.   
  31.             }  
  32.         }  
  33.     }  
  34. }  
Output 

LINQ

Example of Count Operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace AggregationOperations_Demo  
  8. {  
  9.     class Count  
  10.     {  
  11.         static void Main()  
  12.         {  
  13.             using (DBModel db = new DBModel())  
  14.             {  
  15.                 List<Product> listProduct = db.Products.ToList<Product>();  
  16.   
  17.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  18.   
  19.                 foreach (var product in listProduct)  
  20.                 {  
  21.                     Console.WriteLine(product.Product_Id + "\t" + product.Product_Name + "\t\t" + product.Quantity + "\t" + product.Price);  
  22.                 }  
  23.   
  24.                 Console.WriteLine();  
  25.   
  26.                 Console.WriteLine("TOTAL ENTRY \n");  
  27.   
  28.                 int result = listProduct.Count();  
  29.   
  30.                 Console.WriteLine("Total Entry:\t" + result);  
  31.             }  
  32.         }  
  33.     }  
  34. }  
Output

LINQ

Example of Aggregate Operator

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace AggregationOperations_Demo  
  6. {  
  7.     class Aggregate  
  8.     {  
  9.         static void Main()  
  10.         {  
  11.             using (DBModel db = new DBModel())  
  12.             {  
  13.                 List<Product> listProduct = db.Products.ToList<Product>();  
  14.   
  15.                 Console.WriteLine("LIST OF PRODUCTS \n");  
  16.   
  17.                 foreach (var product in listProduct)  
  18.                 {  
  19.                     Console.WriteLine(product.Product_Id + "\t" + product.Product_Name + "\t\t" + product.Quantity + "\t" + product.Price);  
  20.                 }  
  21.   
  22.                 Console.WriteLine();  
  23.   
  24.                 Console.WriteLine("LIST OF PRODCUT \n");  
  25.   
  26.                 string result = listProduct.Aggregate<Product, string, string>("Product Names:\t "+  
  27.                                             String.Empty,// seed value  
  28.                                             (str, p) => str += p.Product_Name + ",",   
  29.                                             str => str.Substring(0, str.Length - 1));  
  30.   
  31.     f;            Console.WriteLine(result);  
  32.                 Console.ReadLine();  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Output
 
LINQ


Similar Articles