Itertools for C# – Cycle and Zip
Continuing our implementation of Python iterator functions in C#, we’ll implement Cycle and Zip this time. Cycle IEnumerable Cycle(IEnumerable iterable) Cycle keeps cycling through the enumerator, that is, it cycles back to the first element when the enumerator is exhausted. You can use it like IEnumerable<int> source = new List<int>() { 1, 2, 3}; foreach(int element in Itertools.Cycle(source)) { Console.WriteLine(element); // prints 1 2 3 1 2 3.. } The implementation is again very straightforward – all we have to do is wrap the foreach over the iterable in an infinite loop. The outer loop while loop creates a new … Continue reading Itertools for C# – Cycle and Zip