Python の itertools.cycle を C# で作る

Pythonitertools.cycleC# で作ってみます。

using System;
using System.Collections.Generic;
using System.Linq;

class Iter {
    public static IEnumerable<T> Cycle<T>(IEnumerable<T> seq) {
        for (;;) {
            bool empty = true;
            foreach (var elt in seq) {
                yield return elt;
                empty = false;
            }

            if (empty) yield break;
        }
    }
}

class Program {
    static void Main() {
        int[] xs = { 1, 2, 3 };
        Console.WriteLine(string.Join(",", Iter.Cycle(xs).Take(10)));
        //=> 1,2,3,1,2,3,1,2,3,1

        Console.WriteLine("[{0}]", string.Join(",", Iter.Cycle(new int[] {})));
        //=> []

        Console.WriteLine(string.Join(",", Iter.Cycle(Enumerable.Range(1, 2)).Take(5)));
        //=> 1,2,1,2,1

        Console.WriteLine(string.Join(",", Iter.Cycle(new List<char>() { 'a', 'b' }).Take(5)));
        //=> a,b,a,b,a
    }
}

実行結果です。

1,2,3,1,2,3,1,2,3,1
[]
1,2,1,2,1
a,b,a,b,a