Alex Rivera | Logout

What is the use of Enumerable.Zip extension method in Linq?

Asked 2011-02-25T21:15:37.160
180

What is the use of Enumerable.Zip extension method in Linq?

Edit
Report

1 Answer

24

It iterates through two sequences and combines their elements, one by one, into a single new sequence. So you take an element of sequence A, transform it with the corresponding element from sequence B, and the result forms an element of sequence C.

One way to think about it is that it's similar to Select, except instead of transforming items from a single collection, it works on two collections at once.

From the MSDN article on the method:

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// This code produces the following output:

// 1 one
// 2 two
// 3 three

If you were to do this in imperative code, you'd probably do something like this:

for (int i = 0; i < numbers.Length && i < words.Length; i++)
{
    numbersAndWords.Add(numbers[i] + " " + words[i]);
}

Or if LINQ didn't have Zip in it, you could do this:

var numbersAndWords = numbers.Select(
                          (num, i) => num + " " + words[i]
                      );

This is useful when you have data spread into simple, array-like lists, each with the same length and order, and each describing a different property of the same set of objects. Zip helps you knit those pieces of data together into a more coherent structure.

So if you have an array of state names and another array of their abbreviations, you could collate them into a State class like so:

IEnumerable<State> GetListOfStates(string[] stateNames, int[] statePopulations)
{
    return stateNames.Zip(statePopulations, 
                          (name, population) => new State()
    
answered 2011-02-25T21:19:04.590

Your Answer