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 have the same name, like Repeat and TakeWhile. I found four functions that weren’t directly available as IEnumerable<T> methods and decided to implement them. Let’s take a look at them, one by one.


IEnumerable<T> Chain<T>(params IEnumerable<T>[] iterables)

Chain returns one flat view of all the enumerators chained together. IEnumerable<T>.Concat does the same thing, but you’ll have to call it multiple times to chain more than one iterator. Chain can be used to do things like

IEnumerable<int> e1 = new List<int>() { 1, 2, 3};
IEnumerable<int> e2 = new List<int>() { 4, 5, 6};
IEnumerable<int> e3 = new List<int>() { 7, 8, 9};

IEnumerable<int> chained = Itertools.Chain(e1, e2, e3);

foreach(int element in chained)
Console.WriteLine(element); // prints 1 2 3 4 5 6 7 8 9

The implementation is fairly straightforward, thanks to the incredibly useful yield statement.

public static IEnumerable<T> Chain<T>(params IEnumerable<T>[] iterables)
   foreach(IEnumerable<T> iterable in iterables)
      foreach (T t in iterable)
         yield return t;

Next up is the Cycle method. We’ll see how it works in the next blog post.

One thought on “Itertools for C#

  1. Hi Senthil, thanks for providing this part of itertools to us. As I am no statistics and math guy (and no Python guy either), I was not able for example to duplicate the “product” function of itertools myself, although I understand its valuable output. Question: Are you working on a more complete itertools implementation for C#?

    With kind regards,


Leave a Reply

Your email address will not be published. Required fields are marked *