×

c# · level 3 · unit 4 · 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

hands out items one at a time.

foreach does not need a list. It needs an : anything that can hand out items one after another. Lists, arrays and LINQ queries all are. Return IEnumerable<T> from a method and callers can loop over it without caring how the items are made.

The neatest way to write one is an : a method that uses yield return. Each yield return hands one item to the loop and pauses the method right there. When the loop asks for the next item, the method carries on from where it paused.

yield break ends the iterator early, like return in a normal method.

using System;
using System.Collections.Generic;

foreach (string slot in Slots(9, 12))
{
    Console.WriteLine(slot);
}

IEnumerable<string> Slots(int from, int to)
{
    for (int hour = from; hour < to; hour++)
    {
        yield return $"{hour}:00";
        yield return $"{hour}:30";
    }
}

Nothing is stored: each time slot is made at the moment the loop asks for it.