Left Joins in LINQ

Filed Under (.NET, Development) by Robert Green on 19-06-2009

Tagged Under : ,

For some reason it seems that I often need to perform a left join in LINQ. Every time I need to do this I find myself scouring the web one more time in order to remember how a left join works in LINQ. So how does it work? The best example that I’ve found is here. The example looks something like this:


1
2
3
4
5
6
7
8
9
10
var list = from r in dc.tblRooms
             join ui in dc.tblUserInfos
             on r.UserName equals ui.UserName into userrooms
             where r.CourseID == 1848
             from ur in userrooms.DefaultIfEmpty()
             select new{
                 FirstName = (ur.FirstName == null) ? "N/A" : ur.FirstName,
                 LastName = (ur.LastName == null) ? "N/A" : ur.LastName,
                 RoomName = r.Name
              };

I like this example a lot because it is very straight forward. Personally I would like to make the statement a bit more generic. In order to do that all we need to remember is that every Left Join has a left table A and a right table B. All the results from the A will be returned regardless of the join with B. In my example I will call table A the LEFT_TABLE and table B the RIGHT_TABLE.


1
2
3
4
5
6
var list =  from LT in LEFT_TABLE
	      join RT in RIGHT_TABLE
	      on LT.key equals RT.KEY into NEW_TABLE
              where <CONDITIONS>
              from NT in NEW_TABLE.DefaultIfEmpty()
              <SELECT_STATEMENT>;

The only problem that may occur with this left join occurs with the DefaultIfEmpty() operator. A better practice would be to pass in a default value so that we can know what to expect in return.