The LINQ Zip Operator

LINQ

I am a strong believer that .NET programmers in general, and Windows Phone programmers in particular need to become proficient in LINQ.  As part of that belief and commitment to the Windows Phone community, I have created a series of postings on  LINQ, and in this posting we take a look at the zip operator.

Zip is a fascinating operator. It is used to thread two lists together. The easiest way to do it is to call Zip on the first list, passing in the name of the second list and then a lambda statement indicating how you want the lists zipped together. The result of Zip is an Enumerable.

Let’s suppose you start with two arrays of strings,

string[] codes = { "AL", "AK", "AZ", "AR", "CA" };
string[] states = 
{
   "Alabama", 
   "Alaska", 
   "Arizona", 
   "Arkansas", 
   "California" 
};

 

A single LINQ statement can stitch the two lists together, according to whatever delegate (lamda expression) you supply,

var CodesWithStates = 
   codes.Zip(
      states, 
      (code, state) => code + ": " + state);

 

Here we call Zip on one of the arrays and pass in two parameters:

  • The second collection to be zipped with the first
  • A delegate indicating how they should be combined

We can display the contents of the resulting Enumerable collection (CodesWithstates) with a for each loop:

foreach ( var item in CodesWithStates )
{
   Console.WriteLine(item);
}

Here’s the output:

AL: Alabama
AK: Alaska
AZ: Arizona
AR: Arkansas
CA: California

 

For the Zip operator to work the two lists do not have to be of the same type, nor of the same length. Here is a quick second example,

int[] codes = Enumerable.Range(1,100).ToArray();
string[] states = 
{
   "Alabama", 
   "Alaska", 
   "Arizona", 
   "Arkansas", 
   "California" 
};

var CodesWithStates = 
      codes.Zip(
            states, (code, state) => code + ": " + state);

foreach ( var item in CodesWithStates )
{
   Console.WriteLine(item);
}

In this second case, the codes array is an array of 100 integers. Zip puts the two disparate lists together until it runs out of one list (in this case states) in which case it terminates. Here’s the output,

1: Alabama
2: Alaska
3: Arizona
4: Arkansas
5: California

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Linq, Mini-Tutorial and tagged . Bookmark the permalink.

5 Responses to The LINQ Zip Operator

Comments are closed.