How to use Left Join in C# Linq

By | May 22, 2017

In this article I will discuss about the how to perform a left join in C# Linq. You may think why to discuss Left join separately in an article. This is due to the reason that LINQ doesn’t provide any keyword like left join in C#.  As you will see there is a workaround to achieve left join in LINQ.

Become an Expert in Programming and Web Development.View all courses!

Before going further you may be interested in the following articles.

In my previous article we performed a join for two sequences. And a simple join in LINQ is inner join by default.

As we saw in that article out of all the employee in the employee list, one of the employee was missing. The employee name was “Albert”.

Now if we want to get the department of the “Albert”, we need to perform the special kind of join as shown in the code below.

The other boiler plate code is same as previous article, like creation of two collection and etc.

In the above code I have created a range variable named “ed”. This range variable will will be used to create a group of the department by the employee name. Since for the employee “Albert” the department is null. The range variable for that employee will be empty.

From whatever sequence we want all the return all the records, we need to keep that collection as the first sequence.

In the above code I want to return all the employee whether or not there is a corresponding department for that employee. I have kept the EmployeeRepository._employee as the outer or left sequence.

Here the inner sequence is i.e DepartmentRepository._department is grouped by the item which we are using for the join i.e emplyee.DepartmentID equals dep.ID. And this grouping is inserted into a range sequence i.e ed.

The result of the above Left Join in C# Linq is shown in the figure below.

Left Join in C# Linq

Left Join in LINQ C#