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
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- EF Linq to Entities Query with groupby sum and min
- LINQ to Lookup with distinct items and count
- c# create or modify file/directory permission: add group read permission using asp.net with mono and apache2
- LINQ where clause combined with Func<> and Foreach
- Group and Sum DataTable
- How to join tables and queries in C# with access database
- Switch `ConnectionStrings` between local and remote with Linq to SQL
- How to sum up values working with c# and Newtonsoft JSON?
- Example for passing First Name and Last Name on Subscribe with MailChimp.net
- ListBox with possibility to group by category and A-Z
- LINQ to Entities - Left outer join with a conditional where clause
- Sum time intervals in Linq To SQL and C#
- Read XML file with LINQ and create object with IEnumerable propety
- Expression tree - join 2 expressions with and
- Help in LINQ query with group by
- Is this LINQ query with averaging and grouping by hour written efficiently?
- LinQ to Entities: Query with four tables JOIN
- Is there a way to create Container Group with diagnostics and identity configs in Azure using latest .NET Core SDK
- Fluent Nhibernate - Join query with group by
- NHibernate Query with joins and group by
- Reading from and conditionally writing to complex XML files with LINQ
- Paging and sorting based on custom .NET properties with Linq to SQL
- LinQ to Entities: Query with five tables JOIN
- linq to sql optimized a group with multiple joins
- LINQ Join table then groupby master table
- Solution for complex LINQ query with ROW_NUMBER() and PARTITION BY
- Combining Join type with Nested type and querying in Elasticsearch 6.x
- How To Add Users to an App Group and Role with Microsoft Graph
- How to Aggregate with GroupBy and wait for results
- LINQ to SQL - multiple left join, group by, left join on same table, count
- (C#) Type or namespace list could not be found while using system.Collections.generic
- How to add a launch condition of searching for a process in a setup project c#?
- How to add textBox programmatically into Grid?
- Force evaluate floating version packages with lock file via MsBuild / csproj
- Why doesn't C# let me index into dynamic like a dictionary?
- UWP MVVM Light Gridview selected item triggers with old values
- The notification has no target applications
- SignalR implementation awaits receiving task
- Using F# portable class library from C# portable library
- Connect to Win CE device From WPF/Win Form Application Without Installing Visual Studio
- Dynamically loaded assembly reference issues
- Cannot open database "dbname" requested by the login. The login failed. Login failed for user "machinname\username"
- How to get current URL of webview in windows 8 Apps | C#, XMAL
- Delegate types and covariance with a generic delegate type
- Increasing request size cause any issue?
- How to determine whether a web page has RSS or not in C#
- C# execute code on other thread
- Does this code snippet use Repository or Adapter pattern?
- Edit Multiple Cells on DataGrid then Save to database
- c# windows service with filewatcher