LINQ is actually a shortened form of Language Integrate Query. LINQ defines features that can be used to retrieve data from any type of data source. This is why LINQ is most important because data itself is the basic foundation of any program and using LINQ, data can be easily retrieve from different types of Data Sources.

How to Use Group by in Linq?

In this post, I will explain to you, group by clause in LINQ to SQL. As we know that grouping is a very powerful feature that converts a collection in groups where each group has a key associated with it if you are a beginner then don’t worry this post if for you.

I have created two table Employee and Department.
Employee Table

Id Name Country Address Salary Department
1 Du monde entier France 67, rue des Cinquante Otages 5000 1
2 Chop-suey Chinese France Hauptstr. 29 2500 2
3 France restauration USA 54, rue Royale 2000 3
4 Howard Snyder UK 2732 Baker Blvd. 2400 2
5 Carlos Hernández USA Carrera 22 con Ave. Carlos Soublette #8-35 3500 1
6 France restauration UK 54, rue Royale 3200 1
7 John Steel USA 2732 Baker Blvd. 2800 2
8 Renate Messner UK Carrera 22 con Ave. Carlos Soublette #8-35 2700 3
9 Horst Kloss UK Rua da Panificadora, 12 2400 3
10 Guillermo Fernández France Carrera 22 con Ave. Carlos Soublette #8-35 3500 1
11 Georg Pipps France 54, rue Royale 3200 3
12 Isabel de Castro USA Av. del Libertador 900 2800 3
13 Bernardo Batista UK Grenzacherweg 237 2700 1

Department

Id Department
1 Marketing
2 Research and Development
3 Accounting and Finance

I want the total salary that I’m paying to employees by Department, how do we achieve this Using group by.
if we have to do it manually, we will take each Marketing Department record and then add the total salary.
Similarly, we will take each Research and Development record and add their salaries. so basically we first group the records by Department and then sum the salary column across that group.
So that’s why we are going to use group by clause. 

Sql Query:

Select Department, SUM(Salary) as TotalSalary
from Employee
Group by Department

Linq Query:

var results = from r in Employees
                         group r by r.Department into gp
                         select new
                         {
                             DepartmentId = gp.Key,
                             TotalSalary = gp.Sum(a => a.Salary)
                         };

            foreach (var r in results)
            {
                Debug.Print(($@"""{r.DepartmentId}"" ""{r.TotalSalary}"""));
            }

Output:

Department TotalSalary
1 17900
2 7700
3 13100
3 13100

C# Linq Group By on Multiple Columns

Let’s take this one more level, not only by Department, but we want to include the Country. For example, in France, how much is the total salary that I’m distributing for each department of Marketing, Research and Development, Accounting, and Finance employees. So we are grouping by multiple columns i .e by Department and Country columns. we are grouping total salary first by country and then by Department.

SQL Query:

Select Country, Department, SUM(Salary) as TotalSalary
from Employee
group by Country, Department

Linq Query:

var results = from r in Employees
                         group r by new { r.Department, r.Country } into gp
                         select new
                         {
                             DepartmentId = gp.Key.Department,
                             Country = gp.Key.Country,
                             TotalSalary = gp.Sum(a => a.Salary)
                         };

            foreach (var r in results)
            {
                Debug.Print(($@"""{r.DepartmentId}"" ""{r.Country}"" ""{r.TotalSalary}"""));
            }

Output:

Country Department TotalSalary
France 1 8500
UK 1 5900
USA 1 3500
France 2 2500
UK 2 2400
USA 2 2800
France 3 3200
UK 3 5100
USA 3 4800

Use Multiple aggregate functions with order by

let’s understand with an example, we are showing the totalsalary by country and Department and Let’s say I want the total number of employees as well.
Now, if we want to find out the total number of employees we can use the Count() function if you look at the Employee table, we’ve got 13 rows.And if I want to find the total number of employees within my Employee table, I can say Employee.count() and we get the total count, which is 13 and we will also use order by clause wit Group By.

Sql Query:

Select Country, Department, SUM(Salary) as TotalSalary,COUNT(Name) as TotalEmployees
from Employee
group by Country, Department
order by TotalSalary

Linq Query:

var results = (from r in employees
                           group r by new { r.Department, r.Country } into gp
                         select new
                         {
                             DepartmentId = gp.Key.Department,
                             Country = gp.Key.Country,
                             TotalSalary = gp.Sum(item => item.Salary),
                             TotalEmployees = gp.Count()
                         }).OrderBy(a=>a.TotalEmployees);

            foreach (var r in results)
            {
                Debug.Print(($@"""{r.Country}"" ""{r.DepartmentId}""  ""{r.TotalSalary}"" ""{r.TotalEmployees}"""));
            }

Output

Country Department TotalSalary TotalEmployees
UK 2 2400 1
France 2 2500 1
USA 2 2800 1
France 3 3200 1
USA 1 3500 1
USA 3 4800 2
UK 3 5100 2
UK 1 5900 2
France 1 8500 2

How to apply the where clause with Group?

In the above scenario ,we want to filter the Group By result, let’s say I want only Research and Development department employee’s salaries, to filter the rows, we can use the where clause, where you can say Department is equal to 2.

Sql Query:

Select Country, Department, SUM(Salary) as TotalSalary,COUNT(Name) as TotalEmployees
from Employee
where Department=2
group by Country, Department
order by TotalSalary

Linq Query:

var results = (from r in employees
                           where r.Department==2
                           group r by new { r.Department, r.Country } into gp
                           select new
                           {
                               DepartmentId = gp.Key.Department,
                               Country = gp.Key.Country,
                               TotalSalary = gp.Sum(item => item.Salary),
                               TotalEmployees = gp.Count()
                           }).OrderBy(a => a.TotalEmployees);

            foreach (var r in results)
            {
                Debug.Print(($@"""{r.Country}"" ""{r.DepartmentId}""  ""{r.TotalSalary}"" ""{r.TotalEmployees}"""));
            }

Output:

Country Department TotalSalary TotalEmployees
UK 2 2400 1
France 2 2500 1
USA 2 2800 1

Use Min and Max aggregate functions with Group By

Lets’ say, I want the min salary that I’m paying to employees by Department.

Sql Query:

Select Department, MIN(Salary) as TotalSalary
from Employee
Group by Department

 

Linq Query:

var results = (from r in employees
                           group r by  r.Department into gp
                           select new
                           {
                               DepartmentId = gp.Key,
                               MinDepartmentSalary = gp.Min(item => item.Salary),
                           });

Output

Department MinDepartmentSalary
1 2700
2 2400
3 2000

Lets’ say, I want the max salary that I’m paying to employees by Department.

Sql Query:


Select Department, Max(Salary) as MinDepartmentSalary
from Employee
Group by Department

Linq Query:

 var results = (from r in employees
                           group r by  r.Department into gp
                           select new
                           {
                               DepartmentId = gp.Key,
                               MaxDepartmentSalary = gp.Max(item => item.Salary),
                           });

            foreach (var r in results)
            {
                Debug.Print(($@"""{r.DepartmentId}""  ""{r.MaxDepartmentSalary}"""));
            }

Output

Department MaxDepartmentSalary
1 5000
2 2800
3 3200

The post Split CSV with columns may contain ‘,’ Comma C# appeared first on Software Development | Programming Tutorials.



Read More Articles