Complete these tasks to reinforce what you learned in this module.
Replace the whole hand-written class with a single iterator method. Countdown(5) should produce 5, 4, 3, 2, 1.
for loop stepping down, with yield return i; inside it. The return type is IEnumerable<int>.using System;
using System.Collections.Generic;
class Program
{
// Make this an iterator that counts down to 1
static IEnumerable<int> Countdown(int from)
{
yield break;
}
static void Main()
{
foreach (var n in Countdown(5))
{
Console.WriteLine(n);
}
}
}
Yield each line, trimmed, until you meet a blank one — then stop, ignoring everything after it. Use yield break.
string.IsNullOrWhiteSpace(line) tells you when to yield break.using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<string> UntilBlank(string[] lines)
{
foreach (var line in lines)
{
// Stop completely at the first blank line,
// otherwise hand back the trimmed line
}
yield break;
}
static void Main()
{
var lines = new string[] { " alpha ", "beta", " ", "gamma" };
foreach (var line in UntilBlank(lines))
{
Console.WriteLine(line);
}
}
}