Thursday, May 24, 2012

LINQ Joins


var employeeRepository = new EmployeeRepository();
var departmentRepository = new DepartmentRepository();

Inner Join (Normal)

var employees =
from employee in employeeRepository.GetAll()
join department in departmentRepository.GetAll()
on employee.DepartmentID equals department.ID
select new {employee.Name, Department = department.Name};

Left Join (Grouping on Departments)

var query =
from d in departmentRepository.GetAll()
join e in employeesRepository.GetAll()
on d.ID equals e.DepartmentID
into ed
select new
{
Department = d.Name,
Employees = ed};

foreach(var group in query)
{
Console.WriteLine(group.Department);
foreach(var employee in group.Employees)
{
Console.WriteLine("\t" + employee.Name);
}
}

Cross Join (for completeness)


var employees =
from employee in employeeRepository.GetAll()
join department in departmentRepository.GetAll()
on employee.DepartmentID equals department.ID
select new {employee.Name, Department = department.Name};

No comments: