Right Join in C# LINQ

By FoxLearn 1/20/2025 3:12:01 AM   5
A right join in C# LINQ is a type of join that returns all elements from the second (right) data source, even if there are no matching elements in the first (left) data source.

However, LINQ only supports left outer joins natively, which behave opposite to right joins. To perform a right join in LINQ, you need to swap the tables or utilize the DefaultIfEmpty method on a group join.

How to Use Right Join in C# LINQ

Define the collections you want to join.

For example, you might use two collections such as students and courses.

var students = new List<Student>
{
    new Student { Id = 1, Name = "John", CourseId = 101 },
    new Student { Id = 2, Name = "Jane", CourseId = 102 },
    new Student { Id = 3, Name = "Mike", CourseId = null },
    new Student { Id = 4, Name = "Alice", CourseId = 103 },
    new Student { Id = 5, Name = "Bob", CourseId = 102 }
};

var courses = new List<Course>
{
    new Course { Id = 101, Name = "Mathematics" },
    new Course { Id = 102, Name = "Science" },
    new Course { Id = 103, Name = "History" },
    new Course { Id = 104, Name = "Geography" }
};

Use the join keyword to perform a group join between the collections based on a common key (e.g., CourseId and Id).

var query = from c in courses
            join s in students on c.Id equals s.CourseId into sc
            from s in sc.DefaultIfEmpty()
            select new
            {
                CourseName = c.Name,
                StudentName = s?.Name ?? "None"
            };

In this example:

  • join Keyword: Combines elements from courses and students based on a common key.

  • into Keyword: Groups matching elements into a collection (sc).

  • DefaultIfEmpty Method: Ensures that all elements from the courses collection are included, even if no matching element exists in students.

  • select Clause: Projects the results into a new anonymous type containing both CourseName and StudentName.

Iterate over the query results and display them using Console.WriteLine.

foreach (var result in query)
{
    Console.WriteLine($"Course {result.CourseName} has student {result.StudentName}");
}

Output:

Course Mathematics has student John
Course Science has student Jane
Course Science has student Bob
Course History has student Alice
Course Geography has student None

By following these steps, you can effectively perform a right join in C# LINQ and handle scenarios where elements from one collection may not have corresponding matches in another.