Zip multiple sequences together

The new Zip extension method in .NET 4.0 is very useful, but what if you want to zip more than two sequences together?

Luckily the implementation of Zip is very straightforward. You can easily implement it yourself if you don’t target .NET 4.0 yet. Likewise it is easy to implement zipping multiple sequences yourself. This allows you to do the following:

byte[] reds = new { 0, 1, 2 };
byte[] greens = new { 3, 4, 5 };
byte[] blues = new { 6, 7, 8 };
var mergedColors = reds.Zip( greens, blues, Color.FromRgb );

mergedColors will contain (0, 3, 6), (1, 4, 7) and (2, 5, 8). With the regular zip operator you would have to write the following:

var mergedColors = reds
    .Zip( greens, ( r, g ) => Color.FromRgb( r, g, 0 ) )
    .Zip( blues, ( c, b ) => Color.FromRgb( c.R, c.G, b ) );

Besides being more complex, it most likely is also less efficient due to the need for the temporary intermediate objects.

The implementation of the Zip for three sequences is as simple as:

public static IEnumerable Zip(
    this IEnumerable first,
    IEnumerable second,
    IEnumerable third,
    Func resultSelector )
        first != null && second != null && third != null && resultSelector != null );

    using ( IEnumerator iterator1 = first.GetEnumerator() )
    using ( IEnumerator iterator2 = second.GetEnumerator() )
    using ( IEnumerator iterator3 = third.GetEnumerator() )
        while ( iterator1.MoveNext() && iterator2.MoveNext() && iterator3.MoveNext() )
            yield return resultSelector(
                iterator3.Current );

Author: Steven Jeuris

I have a PhD in Human-Computer Interaction and am currently working both as a software engineer at iMotions and as a postdoc at the Technical University of Denmark (DTU). This blend of research and development is the type of work which motivates and excites me the most. Currently, I am working on a distributed platform which enables researchers to conduct biometric research 'in the wild' (outside of the lab environment). I have almost 10 years of professional software development experience. Prior to academia, I worked for several years as a professional full-stack software developer at a game development company in Belgium: AIM Productions. I liked the work and colleagues at the company too much to give up entirely for further studies, so I decided to combine the two. In 2009 I started studying for my master in Game and Media Technology at the University of Utrecht in the Netherlands, from which I graduated in 2012.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s