Updated on

An inner join in LINQ pairs each element of one sequence with every element of a second sequence that has the same key, and leaves out the elements that have no match. In C#, we write it with the join clause or the Join() method.

We’ll join two collections in both syntaxes, chain joins across three entities, join on more than one key, and then filter and group the joined data.

To download the source code for this article, you can visit our GitHub repository.

NOTE: Some degree of basic understanding of LINQ is required. We have an excellent article for a quick refresher on LINQ Basic Concepts in C#, do check it out.

Next, let’s grasp the fundamental principles of an inner join.

What Is an Inner Join in LINQ?

An inner join takes two sequences and one key from each side, and returns a result for every pair of elements whose keys are equal. An element that has no partner on the other side does not appear in the result at all.

Microsoft Learn describes the Join() method in database terms: “In relational database terms, the Join method implements an inner equijoin.” Equijoin means the keys are compared for equality, which is why the C# join clause uses the equals keyword and never ==.

Other joins exist too: the group join, the left and right outer joins, the full outer join and the cross join. The inner join is the one we reach for most, because most questions about related data only make sense for rows that match, like which category a course belongs to.

LINQ gives us two ways to write it: the query syntax with join ... on ... equals, and the Join() extension method. Both return the same result.

Inner Join as an Intersection of Two Sets

To understand this, let’s define [1, 3, 5, 7, 9, 11] & [2, 4, 6, 8, 10, 12] as an odd and an even set. Is there any common integer in the two of them? We can say for sure that there is no common integer as an odd integer can never be also an even integer. The intersection between these two sets is empty:

Venn diagram of the odd and even sets with an empty intersection

The odd and even sets share no element.

Now, let’s take [1, 3, 5, 7, 9, 11] & [2, 3, 5, 7, 11] as an odd and a prime set. Some integers are both odd and prime. We can form a new set [3, 5, 7, 11] consisting of common integers from the two sets. The intersection between these two sets is not empty:

Venn diagram of the odd and prime sets with 3, 5, 7 and 11 in the intersection

Only 3, 5, 7 and 11 are in both sets, and they are what an inner join keeps.

Inner join is about the unique relationships between the groups defined based on commonalities such as the relationship between the odd and the prime sets. 

Understanding the basics is essential, but what are some actual problems that can be addressed using inner joins? Let’s examine that.

The Usefulness of Inner Join

Let’s define a Student table that has an Id and a Name:

IdName
1Boba Fett
2Obi-Wan Kenobi
3Darth Vader
4Yoda
5Grogu

Let’s also define a Category table with an Id and a Name of the category:

IdName
1Programming Language
2DevOps
3Database System

Then, let’s add a Course table with an Id, Name and the CategoryId that the course belongs to:

IdNameCategoryId
1PYTHON1
2MSSQL3
3GIT2

Finally, let’s add an Enrolment table that keeps a reference to the Student and the Course they enrolled in using their respective Ids:

IdCourseIdStudentId
133
222
314
421

The final schema of our data is straightforward:

Table schema of the data

The inner join could help us answer questions like these: What is the name of the student with the enrolment id 2? What’s the name of the course in the Enrolment that has a certain Id?

With our human eye, we can easily perform inner joins and say that “Obi-Wan Kenobi is enrolled for MSSQL” or “Enrolment number 4 is about MSSQL”, but in this article, we are going to learn how to answer questions like these programmatically using LINQ, on a larger set of sample data.

How to Join Two Entities in LINQ?

Let’s begin by creating the entities we need. 

The entity Course consists of the Id, Name, and CategoryId properties:

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int CategoryId { get; set; }

    public static IEnumerable<Course> GetDummyCourses() =>
    [
        new() { Id = 1, Name = "CSHARP", CategoryId = 1 },
        new() { Id = 2, Name = "PYTHON", CategoryId = 1 },
        new() { Id = 3, Name = "JAVA", CategoryId = 1 },
        new() { Id = 4, Name = "RUBY", CategoryId = 1 },
        new() { Id = 5, Name = "GO", CategoryId = 1 },
        new() { Id = 6, Name = "MSSQL", CategoryId = 3 },
        new() { Id = 7, Name = "POSTGRES", CategoryId = 3 },
        new() { Id = 8, Name = "MONGODB", CategoryId = 3 },
        new() { Id = 9, Name = "MYSQL", CategoryId = 3 },
        new() { Id = 10, Name = "DOCKER", CategoryId = 2 },
        new() { Id = 11, Name = "JENKINS", CategoryId = 2 },
        new() { Id = 12, Name = "GIT", CategoryId = 2 },
        new() { Id = 13, Name = "KUBERNETES", CategoryId = 2 }
    ];
}

The GetDummyCourses() method gives us the courses for our examples: five programming languages, four databases and four DevOps tools.

Next, let’s create the entity Category, which consists of the Id and Name properties. It also has a helper method, GetDummyCourseCategories():

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public static IEnumerable<Category> GetDummyCourseCategories() =>
    [
        new() { Id = 1, Name = "Programming Language" },
        new() { Id = 2, Name = "DevOps" },
        new() { Id = 3, Name = "Database System" }
    ];
}

To have a look at our dummy categories and courses, we add a static EnrolmentHelper class. It holds every helper method in this article, starting with PrintDummyCourses() and PrintDummyCategories(), where we iterate over the collections and print the result:

public static class EnrolmentHelper
{
    public static void PrintDummyCourses()
    {
        foreach (var course in Course.GetDummyCourses())
        {
            Console.WriteLine(
                $"Id: {course.Id} " +
                $"Course: {course.Name} " +
                $"CategoryId: {course.CategoryId}"
            );
        }
    }

    public static void PrintDummyCategories()
    {
        foreach (var category in Category.GetDummyCourseCategories())
        {
            Console.WriteLine(
                $"Id: {category.Id} " +
                $"Category: {category.Name}");
        }
    }
}

When we invoke the two helper methods, we get the list of courses and the list of categories:

Id: 1 Course: CSHARP CategoryId: 1
Id: 2 Course: PYTHON CategoryId: 1
Id: 3 Course: JAVA CategoryId: 1
Id: 4 Course: RUBY CategoryId: 1
Id: 5 Course: GO CategoryId: 1
Id: 6 Course: MSSQL CategoryId: 3
Id: 7 Course: POSTGRES CategoryId: 3
Id: 8 Course: MONGODB CategoryId: 3
Id: 9 Course: MYSQL CategoryId: 3
Id: 10 Course: DOCKER CategoryId: 2
Id: 11 Course: JENKINS CategoryId: 2
Id: 12 Course: GIT CategoryId: 2
Id: 13 Course: KUBERNETES CategoryId: 2
Id: 1 Category: Programming Language
Id: 2 Category: DevOps
Id: 3 Category: Database System

Storing Course and Category as separate entities provides us with great flexibility, but it isn’t very intuitive from the end-user perspective.

For example, our users would prefer to see the name of the category that a course belongs to, rather than having to guess based on the category ID.

We are going to tackle this issue by framing the relationship to return each course with its respective category name using an inner join on Course and Category with the help of LINQ.

Inner Join Using Query Syntax

LINQ provides us with the query syntax to combine two collections based on a common key:

from <alias_for_sequence_1> in sequence_1
join <alias_for_sequence_2> in sequence_2 
on <alias_for_sequence_1>.<key_for_sequence_1> 
equals <alias_for_sequence_2>.<key_for_sequence_2>
select <object>
{
  ....
}

Using the query syntax, let’s add a method to EnrolmentHelper that creates a new entity combining Course and Category with inner join on CategoryId and Id:

public static IEnumerable<dynamic> GetCoursesWithCategory(
    IEnumerable<Course> courses)
{
    var categories = Category.GetDummyCourseCategories();

    var courseWithCategory =
        from course in courses
        join category in categories on
        course.CategoryId equals category.Id
        select new
        {
            course.Id,
            course.Name,
            CategoryName = category.Name
        };

    return courseWithCategory;
}

We first fetch the list of all the categories using the helper method GetDummyCourseCategories() then we write the LINQ query that combines the courses and categories sequence using the join clause, specifying the course.CategoryId and category.Id as the keys to join on.

Finally, we apply the select clause to form the query result as an anonymous object containing properties Id, Name, and CategoryName taken from the course and category sequences. 

To print the result, we add one more helper to EnrolmentHelper:

public static void PrintCoursesWithCategory(IEnumerable<dynamic> courses)
{
    foreach (var course in courses)
    {
        Console.WriteLine(
            $"Id: {course.Id} " +
            $"Course: {course.Name} " +
            $"Category: {course.CategoryName}"
        );
    }
}

When we call it with the result of GetCoursesWithCategory(), we get:

Id: 1 Course: CSHARP Category: Programming Language
Id: 2 Course: PYTHON Category: Programming Language
Id: 3 Course: JAVA Category: Programming Language
Id: 4 Course: RUBY Category: Programming Language
Id: 5 Course: GO Category: Programming Language
Id: 6 Course: MSSQL Category: Database System
Id: 7 Course: POSTGRES Category: Database System
Id: 8 Course: MONGODB Category: Database System
Id: 9 Course: MYSQL Category: Database System
Id: 10 Course: DOCKER Category: DevOps
Id: 11 Course: JENKINS Category: DevOps
Id: 12 Course: GIT Category: DevOps
Id: 13 Course: KUBERNETES Category: DevOps

Isn’t it great? Now we have all the courses with their respective categories.

Notice that the courses come out in the same order they went in. That order is guaranteed: Join() keeps the order of the first sequence, and for each of its elements, the order of the matches from the second one.

Inner Join Using Method Syntax

Alternatively, LINQ also provides us with the method or fluent syntax:

sequence_1.Join(
sequence_2,
<alias_for_sequence_1> => <alias_for_sequence_1>.<key_for_sequence_1>,
<alias_for_sequence_2> => <alias_for_sequence_2>.<key_for_sequence_2>,
(<variable_1>, <variable_2>) => new
{
    ...
})

Using the method syntax, let’s add GetCoursesWithCategoryName() to EnrolmentHelper. It does exactly the same as GetCoursesWithCategory() but with LINQ method syntax:

public static IEnumerable<dynamic> GetCoursesWithCategoryName(
    IEnumerable<Course> courses)
{
    var categories = Category.GetDummyCourseCategories();

    var courseWithCategoryName = courses.Join(
        categories,
        course => course.CategoryId,
        category => category.Id,
        (course, category) => new
        {
            course.Id,
            course.Name,
            CategoryName = category.Name
        }
    );

    return courseWithCategoryName;
}

Now, if we print the result with the PrintCoursesWithCategory() we get:

Id: 1 Course: CSHARP Category: Programming Language
Id: 2 Course: PYTHON Category: Programming Language
Id: 3 Course: JAVA Category: Programming Language
Id: 4 Course: RUBY Category: Programming Language
Id: 5 Course: GO Category: Programming Language
Id: 6 Course: MSSQL Category: Database System
Id: 7 Course: POSTGRES Category: Database System
Id: 8 Course: MONGODB Category: Database System
Id: 9 Course: MYSQL Category: Database System
Id: 10 Course: DOCKER Category: DevOps
Id: 11 Course: JENKINS Category: DevOps
Id: 12 Course: GIT Category: DevOps
Id: 13 Course: KUBERNETES Category: DevOps

The GetCoursesWithCategoryName(), joins the courses list with the categories list, using the Id property of the category object and the CategoryId property of the course object as the join keys. Finally, it uses the lambda we pass as the fourth argument to build each result.

The choice between the query syntax and method syntax is a matter of personal preference. Neither is faster: the compiler turns this join clause into a call to Join(), so both versions run the same code.

Join Without a Result Selector in .NET 11

Both versions so far end with a result selector that builds a new object. Since .NET 11, Join() has an overload without one. It returns each matching pair as a tuple, which is handy when we only want the two objects side by side.

Let’s add GetCourseCategoryPairs() to EnrolmentHelper:

public static IEnumerable<(Course Outer, Category Inner)> GetCourseCategoryPairs(
    IEnumerable<Course> courses)
{
    var categories = Category.GetDummyCourseCategories();

    return courses.Join(
        categories,
        course => course.CategoryId,
        category => category.Id);
}

The tuple elements are named Outer and Inner, after the two sequences. In Program.cs, we can deconstruct each pair into names that read better:

var pairs = EnrolmentHelper.GetCourseCategoryPairs(Course.GetDummyCourses());

foreach (var (course, category) in pairs.Take(3))
{
    Console.WriteLine($"{course.Name} is a {category.Name}");
}

The first three pairs are:

CSHARP is a Programming Language
PYTHON is a Programming Language
JAVA is a Programming Language

The tuple is a typed result, so the compiler checks course.Name for us. With the dynamic results we used above, a typo in a property name only shows up at runtime. If our project targets an older .NET version, the result selector overloads still do the same job.

So far, we have joined two entities. Can we join more than two?

How Do We Join Multiple Entities in C#?

We’ll explore the practical scenario of enrolling students in various courses to understand how multiple joins can assist us in relating multiple entities and retrieving pertinent data.

First and foremost we need two new entities – Student & Enrolment, let’s add that to our project.

Data Preparation

The Student has Id and Name properties along with a helper method GetDummyStudents() that returns list of students:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public static IEnumerable<Student> GetDummyStudents() =>
    [
        new() { Id = 1, Name = "John" },
        new() { Id = 2, Name = "Abhi" },
        new() { Id = 3, Name = "Rahul" },
        new() { Id = 4, Name = "Nisha" },
        new() { Id = 5, Name = "Mike" },
        new() { Id = 6, Name = "Joana" },
        new() { Id = 7, Name = "Nick" },
        new() { Id = 8, Name = "Julie" },
        new() { Id = 9, Name = "Anita" },
        new() { Id = 10, Name = "Jenny" }
    ];
}

Next, let’s add another entity named Enrolment to capture which student gets enrolled in which course:

public class Enrolment
{
    public int Id { get; set; }
    public int StudentId { get; set; }
    public int CourseId { get; set; }

    public static IEnumerable<Enrolment> GetDummyEnrolment() =>
    [
        new() { Id = 1, StudentId = 1, CourseId = 1 },
        new() { Id = 2, StudentId = 1, CourseId = 8 },
        new() { Id = 3, StudentId = 1, CourseId = 12 },
        new() { Id = 4, StudentId = 2, CourseId = 2 },
        new() { Id = 5, StudentId = 2, CourseId = 3 },
        new() { Id = 6, StudentId = 3, CourseId = 7 },
        new() { Id = 7, StudentId = 3, CourseId = 1 },
        new() { Id = 8, StudentId = 4, CourseId = 9 },
        new() { Id = 9, StudentId = 5, CourseId = 9 },
        new() { Id = 10, StudentId = 6, CourseId = 6 },
        new() { Id = 11, StudentId = 6, CourseId = 5 },
        new() { Id = 12, StudentId = 6, CourseId = 11 },
        new() { Id = 13, StudentId = 7, CourseId = 9 },
        new() { Id = 14, StudentId = 8, CourseId = 12 },
        new() { Id = 15, StudentId = 8, CourseId = 7 },
        new() { Id = 16, StudentId = 9, CourseId = 1 },
        new() { Id = 17, StudentId = 9, CourseId = 10 },
        new() { Id = 18, StudentId = 10, CourseId = 4 },
        new() { Id = 19, StudentId = 10, CourseId = 10 },
        new() { Id = 20, StudentId = 10, CourseId = 8 }
    ];
}

The Enrolment has an Id property, it keeps the reference of the student enrolled with StudentId and the course the student gets enrolled in with CourseId.

Performing the Inner Join

Here is the fun part, our users wish to see all the enrolments with the student name and course name for each enrolment instead of the IDs.

To answer our users’ needs, let’s add GetEnrolmentsRelation() to EnrolmentHelper:

private static IEnumerable<dynamic> GetEnrolmentsRelation(
    IEnumerable<Enrolment> enrolments,
    IEnumerable<Student> students,
    IEnumerable<Course> courses)
{
    return enrolments
        .Join(
            students,
            enrolment => enrolment.StudentId,
            student => student.Id,
            (enrolment, student) => new { enrolment, student }
        )
        .Join(
            courses,
            enrolmentStudentRelation =>
            enrolmentStudentRelation.enrolment.CourseId,
            course => course.Id,
            (enrolmentStudentRelation, course) =>
            new { enrolmentStudentRelation, course }
        );
}

Firstly, we join the enrolments data set with the students data set, using the StudentId property of the enrolment object and the Id property of the student object as the join keys. 

Secondly, we perform a second join that takes the first join result and joins it with the courses data set, using the CourseId property of the enrolment object from enrolmentStudentRelation and the Id property of the course object as the join keys.

As a rule, each subsequent join in a multiple join chain operates on the resultset from the previous join operation, so the second join joins a new collection with the result set obtained from the first join, the third with the second, and so on.

Finally, the result returned is a list of dynamic objects that have the full course object and enrolmentStudentRelation property which in turn contains the full enrolment and student objects instead of just their ids. 

Now, to get each enrollment id, the name of the student, and the name of the course we need to perform a select operation on the join result. Let’s add a new method, GetEnrolments(), to the same class:

public static IEnumerable<dynamic> GetEnrolments(
    IEnumerable<Enrolment> enrolments)
{
    var students = Student.GetDummyStudents();

    var courses = Course.GetDummyCourses();

    var enrolmentsRelation = GetEnrolmentsRelation(
        enrolments,
        students,
        courses);

    var result = enrolmentsRelation.Select(
        e =>
            new
            {
                e.enrolmentStudentRelation.enrolment.Id,
                StudentName = e.enrolmentStudentRelation.student.Name,
                CourseName = e.course.Name,
            }
    );

    return result;
}

The GetEnrolments() uses GetEnrolmentsRelation() and then selects the properties it needs from the result of the join.

It ain’t worth it if we don’t verify the result. Let’s add PrintEnrolments() to EnrolmentHelper. It writes one line per enrolment:

public static void PrintEnrolments(IEnumerable<dynamic> enrolments)
{
    foreach (var enrolment in enrolments)
    {
        Console.WriteLine(
            $"Id: {enrolment.Id}, " +
            $"Student Name: {enrolment.StudentName}, " +
            $"Course: {enrolment.CourseName}"
        );
    }
}

When we pass it the result of GetEnrolments(), we get:

Id: 1, Student Name: John, Course: CSHARP
Id: 2, Student Name: John, Course: MONGODB
Id: 3, Student Name: John, Course: GIT
Id: 4, Student Name: Abhi, Course: PYTHON
Id: 5, Student Name: Abhi, Course: JAVA
Id: 6, Student Name: Rahul, Course: POSTGRES
Id: 7, Student Name: Rahul, Course: CSHARP
Id: 8, Student Name: Nisha, Course: MYSQL
Id: 9, Student Name: Mike, Course: MYSQL
Id: 10, Student Name: Joana, Course: MSSQL
Id: 11, Student Name: Joana, Course: GO
Id: 12, Student Name: Joana, Course: JENKINS
Id: 13, Student Name: Nick, Course: MYSQL
Id: 14, Student Name: Julie, Course: GIT
Id: 15, Student Name: Julie, Course: POSTGRES
Id: 16, Student Name: Anita, Course: CSHARP
Id: 17, Student Name: Anita, Course: DOCKER
Id: 18, Student Name: Jenny, Course: RUBY
Id: 19, Student Name: Jenny, Course: DOCKER
Id: 20, Student Name: Jenny, Course: MONGODB

How Do We Join on Multiple Keys in LINQ?

When one key isn’t enough to match two elements, we join on several keys at once by building an anonymous type on each side. In query syntax, that’s on new { enrolment.StudentId, enrolment.CourseId } equals new { grade.StudentId, grade.CourseId }.

Two elements match only when every part of the key is equal. LINQ compares anonymous types property by property, so this works with no extra code.

The two anonymous types have to match exactly: same property names, same types, same order. If the names differ, the compiler can’t work out the key type and stops with error CS1941. The fix is to rename the properties on one side, for example new { StudentId = grade.Student, CourseId = grade.Course }.

A join “on multiple conditions” that needs something other than equality, such as a date range, can’t go into the join clause. It goes into a where clause after the join.

Our school now records a mark per student and course pair in a Grade:

public class Grade
{
    public int StudentId { get; set; }
    public int CourseId { get; set; }
    public string Mark { get; set; } = string.Empty;

    public static IEnumerable<Grade> GetDummyGrades() =>
    [
        new() { StudentId = 1, CourseId = 1, Mark = "A" },
        new() { StudentId = 1, CourseId = 12, Mark = "B" },
        new() { StudentId = 3, CourseId = 7, Mark = "A" },
        new() { StudentId = 2, CourseId = 1, Mark = "C" }
    ];
}

To find the mark for each enrolment, we have to match both the student and the course. Let’s add GetEnrolmentsWithGrade() to EnrolmentHelper:

public static IEnumerable<dynamic> GetEnrolmentsWithGrade(
    IEnumerable<Enrolment> enrolments)
{
    var grades = Grade.GetDummyGrades();

    var enrolmentsWithGrade =
        from enrolment in enrolments
        join grade in grades on
        new { enrolment.StudentId, enrolment.CourseId }
        equals new { grade.StudentId, grade.CourseId }
        select new
        {
            enrolment.Id,
            enrolment.StudentId,
            enrolment.CourseId,
            grade.Mark
        };

    return enrolmentsWithGrade;
}

The method syntax version passes the same two anonymous types as key selectors:

public static IEnumerable<dynamic> GetEnrolmentsWithGradeMethodSyntax(
    IEnumerable<Enrolment> enrolments)
{
    var grades = Grade.GetDummyGrades();

    return enrolments.Join(
        grades,
        enrolment => new { enrolment.StudentId, enrolment.CourseId },
        grade => new { grade.StudentId, grade.CourseId },
        (enrolment, grade) => new
        {
            enrolment.Id,
            enrolment.StudentId,
            enrolment.CourseId,
            grade.Mark
        });
}

When we print what both methods return, we get the same three lines:

Enrolment: 1, StudentId: 1, CourseId: 1, Mark: A
Enrolment: 3, StudentId: 1, CourseId: 12, Mark: B
Enrolment: 6, StudentId: 3, CourseId: 7, Mark: A

Four grades went in and three came out. Abhi (student 2) has a C for CSHARP (course 1), but he never enrolled in CSHARP. No enrolment has that student and course pair, so the inner join drops his grade.

What happens if the property names differ on the two sides? Say Grade called its properties Student and Course. Then new { enrolment.StudentId, enrolment.CourseId } equals new { grade.Student, grade.Course } doesn’t compile:

error CS1941: The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'Join'.

The two anonymous types are different types, so there is no single key type for the join. Naming the properties on one side, new { StudentId = grade.Student, CourseId = grade.Course }, fixes it.

Thus far, we have built a solid foundation on how to join entities using LINQ. Can we apply other LINQ operators on the join result? 

How Do We Use Join With Common LINQ Operators?

LINQ offers a diverse set of operators, including filtering, grouping, ordering, and more. While it’s not possible to cover all of them, in this section we’ll explore how to filter and group results obtained by joining Enrolment with Student and Course.

For example, let’s suppose our users want to group enrolments based on course Id, with a focus on courses where ID < 5. We already know how to join tables, so the only remaining tasks are to filter and group the results.

Let’s add a method FilterAndGroupEnrolments():

public static IEnumerable<IGrouping<dynamic, dynamic>> FilterAndGroupEnrolments(
    IEnumerable<Enrolment> enrolments)
{
    var students = Student.GetDummyStudents();

    var courses = Course.GetDummyCourses();

    var enrolmentsRelation = GetEnrolmentsRelation(
        enrolments,
        students,
        courses);

    var result = enrolmentsRelation
        .Select(
            e =>
                new
                {
                    e.enrolmentStudentRelation.enrolment.Id,
                    StudentName = e.enrolmentStudentRelation.student.Name,
                    CourseId = e.course.Id,
                    CourseName = e.course.Name,
                }
        )
        .Where(x => x.CourseId < 5)
        .GroupBy(x => x.CourseId);

    return result;
}

Firstly, we combine Enrolment, Course, and Student data using the already defined GetEnrolmentsRelation(). After that, we filter the results to only include courses with an id less than 5. Finally, we group the filtered results by course id.

Notice the return type. Most of the other helpers return IEnumerable<dynamic>, but this one returns IEnumerable<IGrouping<dynamic, dynamic>>. The key is dynamic too, because CourseId comes from a dynamic value.

Why not IEnumerable<dynamic> here as well? Since .NET 9, the class LINQ uses for each group is no longer public, and reading group.Key through dynamic throws a RuntimeBinderException at runtime: “‘object’ does not contain a definition for ‘Key'”. When we type the groups as IGrouping, the compiler reads Key through the public interface, and it works on every version.

Now, let’s add PrintEnrolmentsGroup() to EnrolmentHelper to print the groups:

public static void PrintEnrolmentsGroup(
    IEnumerable<IGrouping<dynamic, dynamic>> enrolmentGroups)
{
    foreach (var group in enrolmentGroups)
    {
        Console.WriteLine($"Enrolments for Course Id: {group.Key}");

        foreach (var enrolment in group)
        {
            Console.WriteLine(
                $"Id: {enrolment.Id}, " +
                $"Student Name: {enrolment.StudentName}, " +
                $"Course: {enrolment.CourseName}"
            );
        }
    }
}

When we pass it the result of FilterAndGroupEnrolments(), we get:

Enrolments for Course Id: 1
Id: 1, Student Name: John, Course: CSHARP
Id: 7, Student Name: Rahul, Course: CSHARP
Id: 16, Student Name: Anita, Course: CSHARP
Enrolments for Course Id: 2
Id: 4, Student Name: Abhi, Course: PYTHON
Enrolments for Course Id: 3
Id: 5, Student Name: Abhi, Course: JAVA
Enrolments for Course Id: 4
Id: 18, Student Name: Jenny, Course: RUBY

Similarly, we can apply other LINQ operators to the join result.

Returning dynamic keeps these examples short. The grouping shows what it costs: the compiler couldn’t warn us, and the IEnumerable<dynamic> version failed only when it ran. In our own projects, a small record type for the joined result gives us compile-time checks and avoids the problem altogether. Our article on the dynamic type in C# covers where dynamic does pay off.

What Is the Difference Between Join and GroupJoin?

Join() returns one flat result per matching pair. If a course has three enrolments, it shows up three times, and a course with no enrolments doesn’t show up at all.

GroupJoin() takes the same two sequences and the same key selectors, but it returns one result per element of the first sequence, together with the collection of its matches. A course with three enrolments shows up once, with a group of three. A course with no enrolments still shows up, with an empty group.

That makes GroupJoin() the right tool when every element of the first sequence belongs in the answer, as in “how many enrolments does each course have?”. In query syntax, it is a join clause followed by into.

Microsoft Learn notes that it has no direct SQL counterpart and can express both inner joins and left outer joins. That empty group is where a left outer join in LINQ starts.

Let’s count the enrolments per course with GroupJoin(). We add GetEnrolmentCountPerCourse() to EnrolmentHelper:

public static IEnumerable<dynamic> GetEnrolmentCountPerCourse(
    IEnumerable<Course> courses)
{
    var enrolments = Enrolment.GetDummyEnrolment();

    return courses.GroupJoin(
        enrolments,
        course => course.Id,
        enrolment => enrolment.CourseId,
        (course, courseEnrolments) => new
        {
            course.Name,
            EnrolmentCount = courseEnrolments.Count()
        });
}

The result selector receives a course and all of its enrolments at once. When we print each course name with its count, we get:

CSHARP: 3
PYTHON: 1
JAVA: 1
RUBY: 1
GO: 1
MSSQL: 1
POSTGRES: 2
MONGODB: 2
MYSQL: 3
DOCKER: 2
JENKINS: 1
GIT: 2
KUBERNETES: 0

All 13 courses are there, in their original order. Nobody enrolled in KUBERNETES, so its count is 0. An inner join between the same two collections would give us 20 rows, one per enrolment, and KUBERNETES wouldn’t be among them. To keep such an element in a flat result, we need a left outer join in LINQ.

Conclusion

To sum up, in this article we have seen an overview of the inner join using LINQ, we covered its what, why, and how. Then, we explored various approaches to constructing LINQ queries and we connected three entities with a chain of joins. Additionally, we briefly examined the usage of other LINQ operators, including filter and group, in conjunction with the inner join.

We also joined on a composite key, saw the tuple-returning Join() overload that arrived in .NET 11, and used GroupJoin() when every course had to appear in the result, even with no enrolments.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and xUnit 2.9.3.