How to use Left Join in C# Linq

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.


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

  • How to achieve group by in C# LINQ.

  • How to achieve inner join in C# LINQ

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.

static void Main(string[] args)
{         
var employeeAndDep = from emplyee in EmployeeRepository._employee
join
dep in DepartmentRepository._department on 
                                                 emplyee.DepartmentID equals dep.ID
into ed
select new { Employee = emplyee.EmployeeName, Department = ed };
                     
foreach (var item in employeeAndDep)
{
Console.WriteLine("Employee Name {0}", item.Employee);

foreach (var item1 in item.Department)
{
Console.WriteLine("     {0} ", item1.Name);
}
                
}
Console.Read();
}

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.



Source: Paper.li

Recent Posts

See All

Domain Name System

The Domain Name System (DNS) is the phonebook of the Internet. Humans access information online through domain names, like nytimes.com or espn.com. Web browsers interact through Internet Protocol (IP)