Cross Join in LINQ


Language Integrated Query (LINQ) is a powerful tool in C# for data manipulation, allowing for efficient and expressive data access and manipulation. One of the operations you can perform with LINQ is the cross join operation, which is common in database queries. This article will guide you through implementing a cross join in LINQ.

Understanding Cross Join

Cross join, also known as Cartesian product, is a type of join operation that matches each row of the first table with every row of the second table. If the first table has n rows and the second table has m rows, the result is a table with n*m rows.

Implementing Cross Join in LINQ

To implement a cross join in LINQ, you can use the from clause twice and then select the fields you want from each source.

Example

Here's an example −

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> colors = new List<string> { "Red", "Green", "Blue" };
      List<string> items = new List<string> { "Pen", "Book", "Glass" };

      var crossJoin = from color in colors
                        from item in items
                        select new { Color = color, Item = item };

      foreach (var element in crossJoin) {
         Console.WriteLine($"{element.Color}, {element.Item}");
      }
   }
}

In this example, we first define two lists: colors and items. We then perform a cross join operation on colors and items using two from clauses. The result is a new sequence of anonymous objects, each with a Color and an Item property. Finally, we print each element in the result.

Output

Red, Pen
Red, Book
Red, Glass
Green, Pen
Green, Book
Green, Glass
Blue, Pen
Blue, Book
Blue, Glass

When to Use Cross Join

A cross join can be useful when you want to generate all possible combinations between two lists. However, keep in mind that the number of results grows rapidly with the size of the input lists, so use this operation wisely.

Conclusion

Cross join is a powerful operation in LINQ that allows you to generate all possible combinations between two sequences. While it can lead to a large number of results, it's a handy tool when you need to explore or generate all possible combinations. Understanding how to perform a cross join in LINQ will open up new possibilities for data manipulation in your C# programming.

Updated on: 24-Jul-2023

359 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements