Thursday, May 24, 2012

LINQ Grouping and Projecting

var repository = new EmployeeRepository();

Comprehensive Query Syntax

var queryByDepartment =
from e in repository.GetAll()
group e by e.DepartmentID
into eGroup
orderby eGroup.Key descending
where eGroup.Key < 3
select new
{
DepartmentID = eGroup.Key,
Count = eGroup.Count(),
Employees = eGroup
};

Extension Methods with Lambda Expressions

var queryByDepartment2 =
repository.GetAll()
.GroupBy(e=>e.DepartmentID)
.OrderByDescending(g=>g.Key)
.Where(g=>g.Key < 3)
.Select(g=>
new
{
DepartmentID = g.Key,
Count = g.Count(),
Employees = g
});

foreach(var group in queryByDepartment2)
{
Console.WriteLine("DID: {0}, Count: {1}",
group.DepartmentID,
group.Count);

foreach(var employee in group.Employees)
{
Console.WriteLine("\t{0}:{1}", employee.DepartmentID, employee.Name);
}
}

No comments: