Join

Performs a specified type of inner join on two sequences.
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)

Parameters

outer: IEnumerable<TOuter>

The first IEnumerable<T> to join.

inner: IEnumerable<TInner>

The second IEnumerable<T> to join.

outerKeySelector: Func<TOuter, TKey>

A function to extract the join key from each element of the first sequence.

innerKeySelector: Func<TInner, TKey>

A function to extract the join key from each element of the second sequence.

resultSelector: Func<TOuter, TInner, TResult>

A function to create a result element from two elements in the sequences being joined.

Returns

IEnumerable<TResult>

An IEnumerable<T> that has elements of type TResult that are obtained by performing an inner join on the two sequences.

Remarks

The Join method performs an inner join. An inner join is a join operation that combines records from two tables (or sequences) based on a related column (or key) between them. Only the records that have matching values in both tables are included in the result.

The Join method in LINQ supports anonymous types, which can be useful for creating intermediate objects that hold the joined data.

This method uses deferred execution.

Example

var departments = new[] {
    new { Id = 1, Name = "Sales" },
    new { Id = 2, Name = "Marketing" },
    new { Id = 3, Name = "Engineering" }
};

var employees = new[] {
    new { Id = 101, Name = "Alice", DepartmentId = 1 },
    new { Id = 102, Name = "Bob", DepartmentId = 2 },
    new { Id = 103, Name = "Charlie", DepartmentId = 1 },
    new { Id = 104, Name = "David", DepartmentId = 4 } // No matching department
};

var query = departments.Join(
    employees,
    department => department.Id,
    employee => employee.DepartmentId,
    (department, employee) => new {
        EmployeeName = employee.Name,
        DepartmentName = department.Name
    }
);

foreach (var item in query)
{
    Console.WriteLine($"Employee: {item.EmployeeName}, Department: {item.DepartmentName}");
}
// Output:
// Employee: Alice, Department: Sales
// Employee: Bob, Department: Marketing
// Employee: Charlie, Department: Sales
.NET Core 2.0, .NET Framework 3.5, .NET Standard 1.0, .NET 5+