LINQ Interview Question #58

How can you join on multiple columns in LINQ?

Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate

Quick Interview Answer

Create matching composite keys on both sides of the join. Anonymous types are commonly used for this purpose, and the corresponding property names and compatible types must match.

Detailed Explanation

Create matching composite keys on both sides of the join. Anonymous types are commonly used for this purpose, and the corresponding property names and compatible types must match.

This is useful when one field alone is not enough to identify the relationship.

Code Example

var result =
    from item in orderItems
    join price in prices
        on new { item.ProductId, item.RegionId }
        equals new { price.ProductId, price.RegionId }
    select new
    {
        item.ProductId,
        price.Amount
    };