LINQ Interview Question #56
How do you perform a left outer join in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
A common LINQ left-join pattern uses GroupJoin followed by SelectMany and DefaultIfEmpty. Query syntax expresses the same pattern with join ... into and a second from clause using DefaultIfEmpty.
Detailed Explanation
A common LINQ left-join pattern uses GroupJoin followed by SelectMany and DefaultIfEmpty. Query syntax expresses the same pattern with join ... into and a second from clause using DefaultIfEmpty.
The outer element is preserved even when there is no matching inner element.
Code Example
var result =
from customer in customers
join order in orders
on customer.Id equals order.CustomerId
into orderGroup
from order in orderGroup.DefaultIfEmpty()
select new
{
customer.Name,
OrderId = order == null ? (int?)null : order.Id
};