×

c# · level 2 · unit 5 · lesson 2

  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

turns every item into something new.

Select runs a lambda on each item and hands back a sequence of the answers. menu.Select(d => d.Name.ToUpper()) turns every dish into its name in capitals. numbers.Select(n => n * 2) doubles every number.

Each LINQ method hands back a sequence, so you can call another straight after it. This is : .Where(...) picks the cheap dishes, then .Select(...) turns those into text. Read a chain from left to right, like a production line.

Neither method changes the original list. They build new sequences and leave menu as it was.

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

var menu = new List<Dish> { new Dish("soup", 4.50m), new Dish("pie", 6.00m), new Dish("salad", 5.25m) };
var shouts = menu.Select(d => d.Name.ToUpper());
Console.WriteLine(string.Join(", ", shouts));
var cheap = menu.Where(d => d.Price < 6).Select(d => $"{d.Name} {d.Price}");
Console.WriteLine(string.Join(" | ", cheap));

record Dish(string Name, decimal Price);

Records and LINQ work well together: each lambda reads a record's properties.