Group all employees by department in CSharp
Description
The following code shows how to group all employees by department.
Example
/*w w w .j a va 2 s . c o m*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Employee : IComparable<Employee>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
public int Id { get; set; }
public override string ToString()
{
return String.Format("Id: {0}, Name: {1} {2}, Dept: {3}", this.Id, this.FirstName, this.LastName, this.Department);
}
int IComparable<Employee>.CompareTo(Employee other)
{
if (other == null)
return 1;
if (this.Id > other.Id)
return 1;
if (this.Id < other.Id)
return -1;
return 0;
}
}
class Program
{
static void Main()
{
List<Employee> empTree = new List<Employee>();
empTree.Add(new Employee { Id = 1, FirstName = "Janet", LastName = "Gates", Department = "IT" });
empTree.Add(new Employee { Id = 2, FirstName = "O", LastName = "G", Department = "Marketing" });
empTree.Add(new Employee { Id = 4, FirstName = "K", LastName = "H", Department = "IT" });
empTree.Add(new Employee { Id = 6, FirstName = "L", LastName = "H", Department = "Sales" });
empTree.Add(new Employee { Id = 3, FirstName = "E", LastName = "L", Department = "Sales" });
empTree.Add(new Employee { Id = 5, FirstName = "D", LastName = "L", Department = "Marketing" });
var employeesByDept = from e in empTree group e by e.Department;
foreach (var dept in employeesByDept)
{
Console.WriteLine("Department: {0}", dept.Key);
foreach (var emp in dept)
{
Console.WriteLine("\t{0} {1}", emp.FirstName, emp.LastName);
}
}
}
}
The code above generates the following result.