GroupBy in Linq
Loading
GroupBy in Linq
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Jun 10, 2026, 8:01 AM
GroupByin LINQ is used to group records that have the same value in a particular column or property.Simple Example
Suppose you have a list of employees:
Group By Department
Reading the Result
Cynthia SathuragiriPosted Jun 8, 2026, 5:05 AM
GroupBy in LINQ is used to group a collection of items based on a key. It is similar to the SQL GROUP BY clause.
Syntax
var result = collection.GroupBy(x => x.Property);
Example 1: Group Employees by Department
var employees = new List
{
new Employee { Id = 1, Name = "John", Department = "IT" },
new Employee { Id = 2, Name = "David", Department = "HR" },
new Employee { Id = 3, Name = "Mike", Department = "IT" },
new Employee { Id = 4, Name = "Sara", Department = "HR" }
};
var groupedEmployees = employees.GroupBy(e => e.Department);
foreach (var group in groupedEmployees)
{
Console.WriteLine($"Department: {group.Key}");
foreach (var employee in group)
{
Console.WriteLine(employee.Name);
}
}
Output:
Department: IT
John
Mike
Department: HR
David
Sara
Example 2: Group and Count
var result = employees
.GroupBy(e => e.Department)
.Select(g => new
{
Department = g.Key,
EmployeeCount = g.Count()
});
foreach (var item in result)
{
Console.WriteLine($"{item.Department} - {item.EmployeeCount}");
}
Output:
IT - 2
HR - 2
Example 3: Multiple Columns Grouping
var result = employees.GroupBy(e => new
{
e.Department,
e.City
});
Equivalent SQL:
SELECT Department, City, COUNT(*)
FROM Employees
GROUP BY Department, City;
Query Syntax
var result =
from e in employees
group e by e.Department into grp
select new
{
Department = grp.Key,
Count = grp.Count()
};
Common Usage with Entity Framework
var warrantySummary = db.tbl_asset_warranty
.GroupBy(w => w.ClaimStatus)
.Select(g => new
{
ClaimStatus = g.Key,
TotalCount = g.Count()
})
.ToList();
This returns the count of warranties grouped by ClaimStatus.
Pankajkumar PatelPosted Jun 5, 2026, 5:39 AM
Hi Yaad Dhakal,
GroupBy in LINQ is used to group elements that share a key.
Syntax
It returns groups of type IGrouping.
Example
Glad to help! Please mark this answer as the accepted answer if it helped you out!