CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// see: https://stackoverflow.com/a/30887187/1016343
public static void Main()
{
Console.WriteLine("===== Example 1 =====");
// 1. Using IEnumerator allows to get item by item
var i=Iterator.IterateOne(x => true); // iterate endless
Console.WriteLine("===== Example 1a =====");
// 1.a) get item by item
i.MoveNext(); Console.WriteLine(i.Current);
i.MoveNext(); Console.WriteLine(i.Current);
Console.WriteLine("===== Example 1b =====");
// 1.b) loop until 100
int j; while (i.MoveNext() && (j=i.Current)<=100) { Console.WriteLine(j); }
// -----------------------
Console.WriteLine("===== Example 2 =====");
// 2. Using IEnumerable makes looping and LINQ easier
var k=Iterator.IterateAll(x => x<100); // limit iterator to 100
Console.WriteLine("===== Example 2a =====");
// 2.a) Use a foreach loop
foreach(var x in k){ Console.WriteLine(x); } // loop
Console.WriteLine("===== Example 2b =====");
// 2.b) LINQ: take 101..200 of endless iteration
var lst=Iterator.IterateAll(x=>true).Skip(100).Take(100).ToList(); // LINQ: take items
foreach(var x in lst){ Console.WriteLine(x); } // output list
}
// 2 iterators, one as IEnumerator, one as IEnumerable
public class Iterator
{
public static IEnumerator<int> IterateOne(Func<int, bool> condition)
{
for(var i=1; condition(i); i++) { yield return i; }
}
public static IEnumerable<int> IterateAll(Func<int, bool> condition)
{
for(var i=1; condition(i); i++) { yield return i; }
}
}
}