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

Itertools for C#

If you are a C# developer and haven’t taken a look at the itertools python module so far, you owe it to yourself to learn about it. It’s a module with functions that operate on what Python calls “iterables” (IEnumerable in C#). Go ahead, take a look at it before reading on. This got me interested about implementing similar functions in C#, using IEnumerable<T>. I fired up VS 2008 and started cranking out the code, only to find that most of the itertools functions are already implemented as extension methods on IEnumerable<T> in .NET 3.5. Some of the functions even … Continue reading Itertools for C#