How to use Join in LINQ with C#

By | May 19, 2017

In this article I will show how to use Join in Linq with C# examples.  Joins in Linq work much like the join in relational database but there are some subtle difference which you will find below.

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

You may find the below article informative.

How to Use Join

Joins are basically used to join two data collections to get the desired results. There are basically two sequences of data. One is outer sequence and other is inner sequence.

In Linq we use equal keyword to join two sequence unlike sql where we use ‘=’ operator.

The benefit of using Join instead of sub query is that it creates a key collection of the inner sequence. Suppose you have Employee and Department collections and you want to join both of them. Department being the inner sequence join will create a key collection for Department sequence and pull out the relevant department for each employee from the key collection.

The key collection is hash table and it improved the performance.

These LINQ join is like the inner join of SQL. We will get only the correlated data from both the sequences and removing out the data which is not present in any of the sequence.

If we have an employee whose department is not present in that case we will not get the particular employee in the result.

Lets see a working example of Join in LINQ.

In the above code I have two repositories for Employee and Department. In my main method I am using both of these repositories to get the department for each employee.  I hope the code is self explanatory.

Lets see the output of the code below.

How to use Join in LINQ

How to use Join in LINQ

As we an see in the result “Albert” is missing from the result set as the corresponding department for this employee is not present.

I hope you will like this article about using join in LINQ with C#.