Wednesday, October 14, 2009

Left Join revisited.

Remember my post on Friday, the 11th September 2009 about LINQ left joins?
Click here to navigate to the post


As I recently found out, should you attempt to left join 2 complex objects, you MUST instantiate the object of which will be null (the right sequence, object).

A better way to explain this is to provide an example.

C# code
-------
List employeeList = new List();
List companyList = new List();

var linqQuery = from eList in employeeList
join cList in companyList on
eList.CompanyId equals cList.Id
into joinEmpCompany
from jec in joinEmpCompany.DefaultIfEmpty(new Company())
select new
{
// insert whatever values you want here.
}

As you can see above, I instantiate a new Company object as there could be instances where the join will produce null results for the right-hand side (Company object).

Instantiating the Company object when using the DefaultIfEmpty function will allow LINQ to execute and not produce Null Reference errors.

No comments:

Post a Comment