Iterate メソッド
初期値と「次の値」を返す関数を引数で受け取り、無限シーケンスを返す Iterate メソッドを作ってみました。
using System; using System.Collections.Generic; using System.Linq; class Iter { public static IEnumerable<T> Iterate<T>(T init, Func<T, T> next) { T x = init; while (true) { yield return x; x = next(x); } } } class Program { static void Display<T>(IEnumerable<T> xs) { Console.WriteLine(string.Join(" ", xs)); } static void Main() { Display(Iter.Iterate(0, e => e + 8).Take(11)); // => 0 8 16 24 32 40 48 56 64 72 80 Display(Iter.Iterate(0, e => e + 8).TakeWhile(e => e <= 80)); // => 0 8 16 24 32 40 48 56 64 72 80 } }
実行結果です。
0 8 16 24 32 40 48 56 64 72 80 0 8 16 24 32 40 48 56 64 72 80