Wednesday, December 2, 2015

LINQ - Group multiple columns or keys

Using .NET linq you can easily group data in a list. This is an example of grouping data based on multiple keys.

This is the class that I created for testing
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public string SubDepartment { get; set; }
public float Salary { get; set; }
}

This is the multi- key grouping using LINQ
/*create employee list*/
List<Employee> emps = new List<Employee>();

/*Add test data */
emps.Add(new Employee() { Name = "Employee 1", Department = "HR", SubDepartment="Recruitment",  Salary = 4000 });
emps.Add(new Employee() { Name = "Employee 2", Department = "HR",SubDepartment="Recruitment", Salary = 4500 });
emps.Add(new Employee() { Name = "Employee 3", Department = "Tech",SubDepartment="Engineering", Salary = 5000 });
emps.Add(new Employee() { Name = "Employee 4", Department = "Tech",SubDepartment="Engineering", Salary = 5200 });

/*group data based on departments*/
List<Employee> newlist = (from x in emps
group x by new { x.Department, x.SubDepartment } into grp
select new Employee()
{
Department = grp.Key.Department,
SubDepartment = grp.Key.SubDepartment,
Salary = grp.Sum(x => x.Salary)
}
).ToList();