Using LINQ Group Join to combine data

Using LINQ Group Join to combine data

linq

23 Articles

Improve

In this article, let's learn about how to use GroupJoin in 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

  1. Introduction
  2. Using LINQ Group Join to combine collections
  3. Summary

Introduction

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 the into keyword similar to SQL. To work with GroupJoin(), we need atleast one property in each collection to share equal value.

LINQ 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 one‑to‑many 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 Product class with following properties - Id, Name
  • We have Sale class with following properties - Id, Price
  • 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 ProductSales collection.
  • Click on GroupJoin Button to view the result.
  • Click on reset to try other combination
Products
Id Name
1 Shirt
2 Shirt
3 Shirt
4 Shirt
5 Shirt
6 Shirt
Sales
Sale Id Product Id Price Color
123 1 1000 Black
789 1 1000 Red
456 2 1000 White
Product Details Sale Details
Sale Id Price Color

Summary

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 IEnumerable or IQueryable types.

  • Linq
  • GroupJoin
  • Combine
  • into