Group By Using Linq

Varshini S
Varshini S used Ask the Experts™
on
I have the below object  List<Employees>
EmployeeID
Name
Designation
DOB
DOJ
Department


How do I use linq to group by the output like below

Designation      NoOfEmployees
Sales                   250
Marketing          100
Finance               25
HR                       15
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Hi Rubha;

Are you wishing to group on Designation or Department?

Author

Commented:
Department
Retired
Distinguished Expert 2017
Commented:
Hi Rubha;

This should give you what you need.

List<Employees> empList = new List<Employees>();
// ... List gets filled


var results = from emp in empList
              group emp by emp.Department into deptGroup
              select new
              {
                  Designation = deptGroup.Key,
                  NoOfEmployees = deptGroup.Count()
              };

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial