How to merge two lists on a common key field using linq in C#

Tuesday, Aug 10, 2021
programming dotnet

The problem

I want to mwerge two lists on a common key field using LINQ.

The solution

The following code snippet demonstartes a solution based on two lists filled with tuples.

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

var customers = new List<(int Customer, string Name)>
{
    (Customer: 1, Name: "Bob"),
    (Customer: 2, Name: "Sam"),
    (Customer: 3, Name: "Rob"),
    (Customer: 4, Name: "Sally")
};
var purchases = new List<(int Customer, string Item)>
{
    (Customer: 1, Item: "Bat"),
    (Customer: 1, Item: "Baseball"),
    (Customer: 3, Item: "Basketball"),
    (Customer: 4, Item: "Hat")
};

var result = customers.Join(purchases, // join customers with purchases 
    tuple => tuple.Customer, // Id to use on customers
    tuple => tuple.Customer, // Id to use on purchases 
    (tuple, valueTuple) => (Customer: tuple.Customer, Name: tuple.Name, Item: valueTuple.Item)); //     Result construction

foreach (var valueTuple in result)
{
    Console.WriteLine($"{valueTuple.Name} (id: {valueTuple.Customer}) bought {valueTuple.Item}");
}

The result is:

Bob (id: 1) bought Bat
Bob (id: 1) bought Baseball
Rob (id: 3) bought Basketball
Sally (id: 4) bought Hat