×

c# · level 3 · unit 3 · lesson 1

  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

A LINQ query is a recipe, not a meal.

var cheap = prices.Where(p => p < 5); does not filter anything yet. It stores a recipe. The work happens later, each time something walks through cheap: a foreach, Count() or string.Join. This is .

So a query sees the data as it is when it runs, not when it was written. Add an item to the list afterwards and the next walk includes it. Walk the query twice and the work is done twice. First stops walking as soon as it has an answer.

When you want the answer fixed, call ToList(). It runs the recipe once and keeps a that later changes do not touch.

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

var prices = new List<int> { 3, 8, 2 };
var cheap = prices.Where(p => p < 5);
var cheapNow = prices.Where(p => p < 5).ToList();
prices.Add(1);
Console.WriteLine(string.Join(", ", cheap));
Console.WriteLine(string.Join(", ", cheapNow));

string.Join(", ", items) glues every item into one line, with , between them.