0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ Join in C# for Combining Collections

Use LINQ Join in C# to combine two collections by matching keys from each collection. The join keyword links elements where keys are equal, producing a new result set with combined data.
📐

Syntax

The basic syntax of LINQ Join uses the join keyword to match keys from two collections. You specify the inner collection, the key selector for each collection, and the result selector to shape the output.

  • outer: The first collection.
  • inner: The second collection to join with.
  • outerKeySelector: Function to select the key from the outer collection.
  • innerKeySelector: Function to select the key from the inner collection.
  • resultSelector: Function to create the result from matching elements.
csharp
var query = from outer in outerCollection
            join inner in innerCollection
            on outer.Key equals inner.Key
            select new { outer, inner };
💻

Example

This example shows how to join two lists: one with students and one with their scores. It matches students by their ID and creates a combined result with student name and score.

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

class Program
{
    static void Main()
    {
        var students = new List<Student>
        {
            new Student { Id = 1, Name = "Alice" },
            new Student { Id = 2, Name = "Bob" },
            new Student { Id = 3, Name = "Charlie" }
        };

        var scores = new List<Score>
        {
            new Score { StudentId = 1, Value = 85 },
            new Score { StudentId = 2, Value = 92 },
            new Score { StudentId = 4, Value = 78 }
        };

        var query = from student in students
                    join score in scores
                    on student.Id equals score.StudentId
                    select new { student.Name, score.Value };

        foreach (var item in query)
        {
            Console.WriteLine($"{item.Name} scored {item.Value}");
        }
    }
}

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

class Score
{
    public int StudentId { get; set; }
    public int Value { get; set; }
}
Output
Alice scored 85 Bob scored 92
⚠️

Common Pitfalls

Common mistakes when using LINQ Join include:

  • Using keys that do not match in type or value, resulting in no matches.
  • Forgetting to use equals keyword between keys.
  • Not projecting the result properly, leading to unexpected output.
  • Assuming join returns all elements; it only returns matching pairs (inner join behavior).

To include all elements from one side, consider GroupJoin or DefaultIfEmpty for left joins.

csharp
/* Wrong: keys have different types or missing equals keyword */
var wrongJoin = from s in students
                join sc in scores
                on s.Id == sc.StudentId  // Error: use 'equals' not '=='
                select new { s.Name, sc.Value };

/* Correct: use 'equals' keyword */
var correctJoin = from s in students
                  join sc in scores
                  on s.Id equals sc.StudentId
                  select new { s.Name, sc.Value };
📊

Quick Reference

Remember these tips when using LINQ Join:

  • Use join with equals to match keys.
  • Join returns only matching pairs (inner join).
  • Use anonymous types or custom objects to shape results.
  • For outer joins, use GroupJoin with DefaultIfEmpty.

Key Takeaways

Use the 'join' keyword with 'equals' to match keys from two collections in LINQ.
LINQ Join returns only elements with matching keys (inner join behavior).
Project the result with 'select' to combine data from both collections.
Ensure key types and values match exactly to get correct join results.
For outer joins, use GroupJoin with DefaultIfEmpty instead of Join.