How to Group in C# Like in SQL

adejimifelix

Felix Adejimi

Posted on December 13, 2019

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();

💖 💪 🙅 🚩
adejimifelix
Felix Adejimi

Posted on December 13, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to Group in C# Like in SQL
csharp How to Group in C# Like in SQL

December 13, 2019