In this article, let's learn about how to use
LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ Join to combine data.
Table of Contents
When working with two collections, we can combine them using LINQ
GroupJoin() method. This will join elements between two or more
collections and gives a single collection representing one-to-many relationship.
GroupJoin() can also be done using Query Synatx using
into keyword similar to SQL. To work with
GroupJoin(), we need atleast one property in each
collection to share equal value.
GroupJoin() is used to answer questions about collection such as
- Joining collections using common key value to define one-to-many relationship between them
- Grouping Menu and Sub Menu in Navigation bar in UI
- Grouping Items with parent in Accordion
- Joining Order and Order Items
Using LINQ Group Join to combine collections
GroupJoin() is a very popular thing, a very common thing that you would do in many applications where you have a
relationship. We can 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 element and their associated collection values. For Example, new collection of customerOrders for each customer.
Code Sample - LINQ GroupJoin Objects with Single Field
Demo - LINQ GroupJoin Clause with Objects Demo
Let's try LINQ GroupJoin with Objects
- We have
Productclass with following properties -
- We have
Saleclass with following properties -
- The tables are loaded with product and sale collection.
- The Key Expression here is the
Product ID. GroupJoin() will combine Products and Sales and return new
- Click on GroupJoin Button to view the result.
- Click on reset to try other combination
|Sale Id||Product Id||Price||Color|
|Product Details||Sale Details|
In this article we learn't how to combine data between collections using
GroupJoin. This allows you to group elements from one
collection with elements from another collection based on a specified key representing one-to-many relationship. All these can be used with any