Blog

Using LINQ's Zip query operator

By Vulpes Blogs | LINQ Apr 18, 2012
How to use LINQ's Zip query operator
The Zip query operator was not included in LINQ initially but was added as an afterthought in .NET 4.0.

It operates on two sequences in parallel, returning another sequence whose elements are the result of applying a method to corresponding pairs of elements from the input sequences. 

The name appears to have been chosen because it works a bit like a zipper.

A simple example should help to make it clear how it works.

Suppose you have two arrays of equal length. The first array contains some numbers, the second array contains some names corresponding to those numbers and you'd like to produce an array of strings combining this information.

The following program does that:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
       int[] numbers = {1, 2, 3, 4, 5, 6};
       string[] names = {"Dave", "Jack", "Sam", "Don", "John", "Fred"};
       string[] combined = numbers.Zip(names, (number, name) => number + " : " + name).ToArray();
       foreach(string c in combined) Console.WriteLine(c);
       Console.ReadKey();
    }
}
   
The output is:

1 : Dave
2 : Jack
3 : Sam
4 : Don
5 : John
6 : Fred


If the input sequences are of unequal length, then the output sequence will have the length of the smaller sequence and the additional elements of the other sequence will be ignored. So, if we change the integer array in the above code to:

   int[] numbers = {1, 2, 3, 4, 5, 6, 7};

or we change the string array to:

   string[] names = {"Dave", "Jack", "Sam", "Don", "John", "Fred", "Bill"};

then the output will be exactly the same as above.

COMMENT USING