Using LINQ Join to combine data
LINQ
26 Articles
In this article, let's learn about how to use Join in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ Concat to combine data.
Table of Contents
- Introduction
- Using LINQ Join to combine primitive types
- Using LINQ Join to combine collections using single field
- Using LINQ Join to combine collections using multiple fields
- Summary
Introduction
When working with two collections, we can combine them using LINQ Join() method. This will join elements between two or more collections and gives a single collection. Join() also know as Equi Join or Inner Join in SQL. To work with Join(), we need atleast one property in each collection to share equal value.
LINQ Join() is used to answer questions about collection such as
- Joining collections using common key value to define relationship between them
- Joining Customer and their Orders
- Joining Order and Order Items
Using LINQ Join to combine primitive types
Primitive data types like int, decimal, string, etc can just combine the values against other equal values in the collection
Code Sample - LINQ Join Primitive Types
Using LINQ Join to combine Collections using single field
We can use Join() to combine elements between two or more sequences (arrays, lists, etc.) based on a key value. The result is a new sequence that contains elements with the matching key and their associated values.
Code Sample - LINQ Join Objects with Single Field
Using LINQ Join to combine Collections using multiple fields
So for joining collections with more than one field, the key selector condition will have an anonymous object containing multiple fields to compare.
Code Sample - LINQ Join Objects with Multiple Fields
Summary
In this article we learn't how to combine data between collections using Join. This can be used to combine items between collection and return a new collection. This can be done using the key selector. We can have single key selector or multiple key selector as anonymous object. All these can be used with any IEnumerable or IQueryable types.