DotNetLover DotNetLover - 1 month ago 10
C# Question

Group By Department and get number of employees present in that department

I am trying to write a query to get distinct department and number of Employees associated with that department(count)

But I'm not able to find exact query in linq:

var empname = new List<EmpName>();
var empadd = new List<EmpAddress>();
var empsal = new List<EmpSalary>();
var empdep = new List<EmpDepartment>();

empdep.Add(new EmpDepartment { EmployeeID = 101, Department = "CIV" });
empdep.Add(new EmpDepartment { EmployeeID = 105, Department = "CIV" });
empdep.Add(new EmpDepartment { EmployeeID = 106, Department = "CIV" });

empdep.Add(new EmpDepartment { EmployeeID = 102, Department = "AEI" });
empdep.Add(new EmpDepartment { EmployeeID = 107, Department = "AEI" });


empdep.Add(new EmpDepartment { EmployeeID = 103, Department = "IES" });
empdep.Add(new EmpDepartment { EmployeeID = 202, Department = "IES" });
empdep.Add(new EmpDepartment { EmployeeID = 203, Department = "IES" });

empdep.Add(new EmpDepartment { EmployeeID = 104, Department = "PIE" });
empdep.Add(new EmpDepartment { EmployeeID = 208, Department = "PIE" });


var results = (from d in empdep
group d.Department by d.EmployeeID into g
select new EmpDetails
{
Department = g.Key.ToString(),
DeptCount = g.Count()
}).ToList();

Answer Source

You can use:

var groupedEmploeesByDepartment = empdep.GroupBy(x => x.Department).Select(x => new { Department = x.Key, EmployeesCount = x.Count() });

The information now is in IEnumerable of anonymous type defined by a Department and EmployeesCount properties.