Linq Join with Multiple Data Sources in C#
In this article, I am going to discuss how to perform Linq Join with Multiple data sources in C# with some examples. I strongly recommended you to read our previous article before proceeding to this article where we discussed how to perform Linq Join with two data sources in C# with some examples.
Data Sources used in this Demo:
We are going to use the following three data sources in this demo.
Here the AddressId property of the Employee Data Source points to the ID property of the Address Data Source. Similarly, the DepartmentId property of the Employee Data Source refers to the ID property of the Department Data Source.
Now we need to fetch the following data from the above three data sources. Notice, we only required to fetch the data which exist in all the three data sources.
As you can see, we need to fetch only the employees with employee IDs 1, 2, 3, 9, 10, and 11. This is because these 6 employees are present in all the data sources and while we are performing the Linq Inner join, then it only fetches the records which exist in both the data sources.
Creating Data Sources:
Create a class file and then copy and paste the following code which will create the required models with the required data.
Joining three Data Sources using Query Syntax in Linq:
The following diagram shows how to join three data sources using Linq Query Syntax:
If you want to join the fourth data source then you need to write another join within the query.
The complete example is given below.
Using Method syntax to perform Join using Multiple Data Sources:
Let see how to rewrite the same example using Method syntax. Using method syntax it is a little difficult to write the join query using more than two data sources. The following image shows how to write the query to fetch data from three data sources using Method syntax.
The complete code is given below.
It will give you the same output as the previous example.
Note: If you want to fetch the data from two data sources then you can use either the Method syntax or Query Syntax. But if you want to fetch the data from more than two data sources then it is easier to use the Query syntax rather than the Method syntax.
In the next article, I am going to discuss the Group Join in Linq with some examples. In this article, I try to explain how to perform Linq Joins with Multiple data sources in C#. I hope you understood how to join multiple data sources using Linq in C#.