views:

1036

answers:

3

Could someone give me an example of how to perform a left join operation using LINQ/lambda expressions?

+6  A: 

The LINQ to SQL samples page on MSDN gives an example of how to accomplish this. The code should be pretty much identical for LINQ to Objects.

The key here is the call to DefaultIfEmpty.

Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

If you need help converting that to C#, just ask.

Noldorin
+2  A: 

Here is an example of a left join in LINQ.

Reed Copsey
A: 

For instance:

IQueryable<aspnet_UsersInRole> q = db.aspnet_Roles
                    .Select(p => p.aspnet_UsersInRoles
                        .SingleOrDefault(x => x.UserId == iduser));

Will give you a list of roles from the asp.net membership, with nulls where it doesn't match the specified user (iduser key)

Francisco