×

c# · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Join pairs up items from two lists that share a key.

Real data lives in separate lists: customers in one, orders in another, linked by an id. A join matches them up. Join takes the second list, a key selector for each side, and a : a lambda that builds one result from each matching pair.

orders.Join(customers, o => o.CustomerId, c => c.Id, (o, c) => ...) reads: for each order, find the customers whose Id equals its CustomerId. An order with no matching customer is left out, and results keep the order of the first list.

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

var customers = new List<Customer> { new Customer(1, "Ana"), new Customer(2, "Ben") };
var orders = new List<Order>
{
    new Order(1, "lamp"), new Order(2, "rug"), new Order(1, "mug"), new Order(5, "sofa"),
};
var receipts = orders.Join(customers, o => o.CustomerId, c => c.Id, (o, c) => $"{c.Name} bought a {o.Item}");
foreach (string receipt in receipts)
{
    Console.WriteLine(receipt);
}

record Customer(int Id, string Name);
record Order(int CustomerId, string Item);

Customer 5 does not exist, so the sofa gets no receipt.