c# · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Pets and owners. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
using System.Linq;
var owners = new List<Owner> { new Owner(1, "Sam"), new Owner(2, "Kim"), new Owner(3, "Lee") };
var pets = new List<Pet> { new Pet("Rex", 2), new Pet("Tom", 2), new Pet("Bo", 9) };
var pairs = pets.Join(owners, p => p.OwnerId, o => o.Id, (p, o) => $"{p.Name}-{o.Name}");
Console.WriteLine(string.Join(" ", pairs));
record Owner(int Id, string Name);
record Pet(string Name, int OwnerId);
your turn
Your turn. Label the parcels.
On line 7, write the result selector: a lambda that takes a parcel and its town, then builds one label naming both.
output
press run to see what happens
fix it
The receipts will not compile. Can you fix it?
output
press run to see what happens
- C# says
Orderhas noIdon line 7. Which list does the first key selector read from? - The first key selector reads from
orders, the list you start with. The second reads fromcustomers. - Swap the two key selectors on line 7, so
o => o.CustomerIdcomes first, then run.
nailed it
you can join data from two lists. :D
Joinmatches items from two lists by a shared key.- The first key selector reads the first list.
- Items without a match are left out.
new words in your collection
- result selector
This lesson isn’t saved. A free account remembers every lesson you finish.