LINQ Cross Join

LINQ Cross Join in C# with Examples

In this article, I am going to discuss LINQ Cross Join in C# using both Method and Query Syntax with Examples. Please read our previous article where we discussed LINQ Full Outer Join in C# with Examples.

What is Cross Join?

When combining two data sources (or you can say two collections) using Cross Join, then each element in the first data source (i.e. first collection) will be mapped with each and every element in the second data source (i.e. second collection). So, in simple words, we can say that the Cross Join produces the Cartesian Products of the collections or data sources involved in the join.

In Cross Join we don’t require the common key or property which is used to specify the Join Condition. And moreover, there is no filtering of data. So, the total number of elements in the result set will be the product of the two data sources involved in the join. If the first data source contains 5 elements and the second data source contains 3 elements then the resultant sequence will contain (5*3) 15 elements.

Examples to Understand LINQ Cross Join:

Let us understand How to Implement Cross Join in LINQ with Examples. We are going to use the following Student and Subject model classes to understand the LINQ Cross Join in C#. Please create a class file with the name Student.cs and then copy and paste the following code into it. This is a very simple class having two properties and one method returning a hard-coded collection of students which is going to be one of our data sources.

using System.Collections.Generic;
namespace LINQCrossJoinDemo
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public static List<Student> GetAllStudents()
        {
            return new List<Student>()
            {
                new Student { ID = 1, Name = "Preety"},
                new Student { ID = 2, Name = "Priyanka"},
                new Student { ID = 3, Name = "Anurag"},
                new Student { ID = 4, Name = "Pranaya"},
                new Student { ID = 5, Name = "Hina"}
            };
        }
    }
}

Next, create another class file with the name Subject.cs and then copy and paste the following code into it. This is also a very simple class having two properties and one method returning a hard-coded collection of subjects which is going to be another data source.

using System.Collections.Generic;
namespace LINQCrossJoinDemo
{
    public class Subject
    {
        public int ID { get; set; }
        public string SubjectName { get; set; }

        public static List<Subject> GetAllSubjects()
        {
            return new List<Subject>()
            {
                new Subject { ID = 1, SubjectName = "ASP.NET"},
                new Subject { ID = 2, SubjectName = "SQL Server" },
                new Subject { ID = 5, SubjectName = "Linq"}
            };
        }
    }
}
Example to Understand LINQ Cross Join Using Query Syntax in C#

Let us see how to implement LINQ Cross Join Using Query Syntax in C#. The following example does the Cross Join between the Student with Subject Data Sources using Query Syntax. Here, we don’t need to use any “join” operator or we don’t need to use the “on” operator and we don’t need to specify the joining condition i.e. no common property is required.

using System.Linq;
using System;
namespace LINQCrossJoinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Cross Join using Query Syntax
            var CrossJoinResult = from student in Student.GetAllStudents() //First Data Source
                                  from subject in Subject.GetAllSubjects() //Cross Join with Second Data Source
                                  //Projecting the Result to Anonymous Type
                                  select new
                                  {
                                      StudentName = student.Name,
                                      SubjectName = subject.SubjectName
                                  };

            //Accessing the Elements using For Each Loop
            foreach (var item in CrossJoinResult)
            {
                Console.WriteLine($"Name : {item.StudentName}, Subject: {item.SubjectName}");
            }

            Console.ReadLine();
        }
    }
}
Output:

Example to Understand LINQ Cross Join Using Query Syntax in C#

We have 5 students in the student’s collection and 3 subjects in the subject’s collection. In the result set, we have 15 elements, i.e. the Cartesian product of the elements involved in the joins. Now, instead of projecting the result to an Anonymous Type, we can also project the result to a named type. Let us understand how can we do this. For this, first, create a class file with the name StudentSubject.cs and then copy and paste the following code into it. As in the result set, we need two properties, so we have created the following class with the required two properties.

namespace LINQCrossJoinDemo
{
    public class StudentSubject
    {
        public string StudentName { get; set; }
        public string SubjectName { get; set; }
    }
}

Next, modify the Main method of the Program class and now, instead of projecting the result to the anonymous type, we are projecting the result to the StudentSubject type.

using System.Linq;
using System;
namespace LINQCrossJoinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Cross Join using Query Syntax
            var CrossJoinResult = from student in Student.GetAllStudents() //First Data Source
                                  from subject in Subject.GetAllSubjects() //Cross Join with Second Data Source
                                  //Projecting the Result to Anonymous Type
                                  select new StudentSubject
                                  {
                                      StudentName = student.Name,
                                      SubjectName = subject.SubjectName
                                  };

            //Accessing the Elements using For Each Loop
            foreach (var item in CrossJoinResult)
            {
                Console.WriteLine($"Name : {item.StudentName}, Subject: {item.SubjectName}");
            }

            Console.ReadLine();
        }
    }
}

With the above changes in place, now, run the application and you will get the same output as the previous example as shown in the below image.

LINQ Cross Join in C# with Examples

Example to Understand LINQ Cross Join Using Method Syntax in C#

In order to implement the LINQ Cross Join using Method Syntax, we need to use either the SelectMany() method or the Join() method as shown in the below example.

using System.Linq;
using System;
namespace LINQCrossJoinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Cross Join using SelectMany Method
            var CrossJoinResult = Student.GetAllStudents()
                        .SelectMany(sub => Subject.GetAllSubjects(),
                         (std, sub) => new
                         {
                             StudentName = std.Name,
                             SubjectName = sub.SubjectName
                         });

            //Cross Join using Join Method
            var CrossJoinResult2 = Student.GetAllStudents()
                        .Join(Subject.GetAllSubjects(),
                            std => true,
                            sub => true,
                            (std, sub) => new
                            {
                                StudentName = std.Name,
                                SubjectName = sub.SubjectName
                            }
                         );


            foreach (var item in CrossJoinResult2)
            {
                Console.WriteLine($"Name : {item.StudentName}, Subject: {item.SubjectName}");
            }

            Console.ReadLine();
        }
    }
}

It will give you the same output as the previous example as shown in the below image.

Example to Understand LINQ Cross Join Using Method Syntax in C#

Instead of projecting the result to an Anonymous Type, we can also project the result to a named type. We have already created a class called StudentSubject. Let us project the result to this StudentSubject type. To do so, modify the Main method of the Program class as follows.

using System.Linq;
using System;
namespace LINQCrossJoinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Cross Join using SelectMany Method
            var CrossJoinResult = Student.GetAllStudents()
                        .SelectMany(sub => Subject.GetAllSubjects(),
                         (std, sub) => new StudentSubject
                         {
                             StudentName = std.Name,
                             SubjectName = sub.SubjectName
                         });

            //Cross Join using Join Method
            var CrossJoinResult2 = Student.GetAllStudents()
                        .Join(Subject.GetAllSubjects(),
                            std => true,
                            sub => true,
                            (std, sub) => new StudentSubject
                            {
                                StudentName = std.Name,
                                SubjectName = sub.SubjectName
                            }
                         );
            
            foreach (var item in CrossJoinResult2)
            {
                Console.WriteLine($"Name : {item.StudentName}, Subject: {item.SubjectName}");
            }

            Console.ReadLine();
        }
    }
}

Run the application and you will get the same output.

In the next article, I am going to discuss the LINQ Element Operators in C# with Examples. In this article, I try to explain how to implement Cross Join in LINQ using both Method and Query Syntax with Examples. I hope you enjoy this LINQ Cross Join in C# with Examples article.

2 thoughts on “LINQ Cross Join”

Leave a Reply

Your email address will not be published. Required fields are marked *