Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pankajkumar PatelRank #181 · 13.4K reputationPosted Jun 5, 2026, 1:39 AM EDT
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!
Cynthia SathuragiriRank #937 · 2.2K reputationPosted Jun 8, 2026, 1:05 AM EDT
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.
Tuhin PaulRank #7 · 71.9K reputationPosted Jun 10, 2026, 4:01 AM EDT
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