by Svetlozar Angelov
23. December 2009 11:16
If you are familiar with SQL, there is nothing interesting in performing inner joins, here is an example (on AdventureWorks)
AdventureWorksDataContext dc = new AdventureWorksDataContext();
var employees =
from employee in dc.Employees
join contact in dc.Contacts on employee.ContactID equals contact.ContactID
select new
{
Firstname = contact.FirstName
, LastName = contact.LastName
, Gender = employee.Gender
};
foreach (var employee in employees)
Console.WriteLine("Firstname: {0}, LastName: {1}, Gender: {2}",
employee.Firstname, employee.LastName, employee.Gender);
To perform a left outer join you need to fetch with DefaultIfEmpty() on the group join. That way you get the nulls(converted to default values).
var employees =
from employee in dc.Employees
join contact in dc.Contacts
on employee.ContactID equals contact.ContactID
into joinedEmployees
from jEmployee in joinedEmployees.DefaultIfEmpty()
select new
{
Firstname = jEmployee.FirstName
, LastName = jEmployee.LastName
, Gender = employee.Gender
};
foreach (var employee in employees)
Console.WriteLine("Firstname: {0}, LastName: {1}, Gender: {2}",
employee.Firstname, employee.LastName, employee.Gender);