Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

Suppose you have a tblRoom and tblUserInfo. Now, you need to select all the rooms regardless of whether the room has user information or not. This calls for a LEFT JOIN which will select everything from the LEFT side (the room side) regardless of the join on the right side. Here is the example.

 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
                              
                           };

The anonymous type replaces the "null" FirstName and LastName with "N/A" (not available).

Posted on Monday, April 7, 2008 7:45 AM | Back to top


Comments on this post: LEFT JOINS and DefaultIfEmpty Operator in LINQ

# re: LEFT JOINS and DefaultIfEmpty Operator in LINQ
Requesting Gravatar...
You should be able to simplify this even further with "??" operator...

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 ?? "N/A",
LastName = (ur.LastName ?? "N/A",
RoomName = r.Name
};
Left by The Wolf on Apr 07, 2008 7:53 AM

# re: LEFT JOINS and DefaultIfEmpty Operator in LINQ
Requesting Gravatar...
Ahh! yes.

Thanks!
Left by Mohammad Azam on Apr 07, 2008 8:33 AM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net | Join free