Inner Join Example in LINQ and C#

Let see an example of using the Join method in LINQ and C#. The Join method performs an inner equijoin on two sequences, correlating the elements of these sequences based on matching keys. It is called equijoin, since we are testing for equality using the equals operator.

If you are familiar with relational databases, then in an inner join, each element of the first collection appears one time for every matching element in the second collection. If an element in the first collection has no matching elements, it does not appear in the join result set. The Join method in LINQ does the same.

We will using two classes Book and Order and use the Join operator on them and see the results. Here’s some sample data:

In the code shown above, the query uses the join clause to match Book objects with Order objects testing it for equality using the equals operator.The select clause defines how the result will appear using anonymous types that consist of the BookID, Book Name and Order Payment Mode.

OUTPUT

As you can see, ‘DevCurry.com Developer Tips’ and ‘Spiritual Gurus’ are listed twice as the books have two orders each. However ‘.NET and COM for Newbies’ does appear in the results, since there are no orders for that book.

In this example, we saw how to do an Inner Join in LINQ. In an upcoming article, we will see how to do a Left Outer Join in LINQ.