Complete these tasks to reinforce what you learned in this module.
Write the iterator so that the counter records how many times the sequence was enumerated. Main enumerates it twice and prints the counter.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int _calls;
static IEnumerable<int> Source()
{
// Record that an enumeration has begun, then hand back 1, 2, 3
yield break;
}
static void Main()
{
var seq = Source();
seq.Count();
seq.Sum();
Console.WriteLine(_calls);
}
}
Same sequence, same two operations — but the source must run exactly once. Change only Main.
ToList() before using it.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int _calls;
static IEnumerable<int> Source()
{
_calls++;
yield return 1;
yield return 2;
yield return 3;
}
static void Main()
{
var seq = Source();
seq.Count();
seq.Sum();
Console.WriteLine(_calls);
}
}
Print how many even numbers there are, then each of them — while the source runs only once. Its producing message must appear exactly one time.
List<int> first, then use it for both the count and the loop.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> Evens()
{
Console.WriteLine("producing");
yield return 2;
yield return 4;
yield return 6;
}
static void Main()
{
// Print the count, then every item — reading the source only once
}
}