DEV Community

Felix Adejimi
Felix Adejimi

Posted on

How to Group in C# Like in SQL

The code snippet below demonstrates how to group object in-memory clean and accurate. Feel free to adapt to your usage in your production project.

StringBuilder builder = new StringBuilder("SELECT s.EmployeeId, s.DepartmentName, s.BasicSalary FROM EmployeeSalary s ");

var employeeSalary = SqlAccess.Get(builder.ToString());
var totalDepartmentSalary = (from s in employeeSalary
group s by s.DepartmentName into g
select new { DepartmentName = g.Key
,TotalEmployee = g.Count()
,TotalBasicSalary = g.Sum(b => b.BasicSalary) }).ToList();

totalDepartmentSalary.ForEach(p => {
Console.Write($"Department: {p.DepartmentName} ");
Console.Write($"Number of Employees: {p.TotalEmployee} ");
Console.WriteLine($"Total Basic Salary: {p.TotalBasicSalary.ToString("N2")}");
});
Console.ReadKey();

Top comments (0)