Left outer join in C# Linq query

By | September 20, 2014

Left joins are such a common occurrence in data access programs. There is no direct LINQ operator or syntax mapped for left joins. However, there is an extension method DefaultIfEmpty() which can be employed to perform a left outer join using LINQ syntax.

DefaultIfEmpty basically returns a single element sequence with associated type’s default value in case source sequence is empty.

For ex: in code snippet below, DefaultIfEmpty returns null if no match found in related employee_associations object for given employeeId since employee_associations is a reference type

Following query attempts to retrieve optional employee_associations and employee_discounts which are perfect candidates for left join because employee may or may not have discounts and associations.

Left outer join always return each element in first collection (employees), regardless of whether it has any matching elements in the second collection (employee_associations) or (employee_discounts)

Leave a Reply

Your email address will not be published. Required fields are marked *