BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 4.0+

LINQ Zip Operator

In the .NET framework version 4.0 Microsoft introduced the Zip method to the set of standard query operators. This extension method combines pairs of values from two sequences to generate a third set of values.

Combining Sequences

In an earlier article I described a custom LINQ operator that combines two sequences of values by iterating through both and using a Func delegate to process the current items from each and project the results into a new sequence. In the .NET framework version 4.0, Microsoft introduced the Zip standard query operator, which performs a similar function without the need for custom code.

Zip cycles through two sequences using deferred execution. The items at the same index are paired and each pair is transformed using a function that is usually provided as a lambda expression. This continues until all of the items in either sequence have been processed. If one sequence has more elements than the other, the extra elements are not projected into the new sequence. NB: This is the key difference between Zip and the custom Combine method, which continues projection using default values for the exhausted sequence.

Examples

For the first example we'll zip together two sequences containing the same number of elements, where each sequence contains the same data type. In the code below you can see that the Zip operator is used as an extension method of the first array. The second array is passed to the first parameter. The second argument specifies the projection function that is used to generate the items in the resultant collection. In this case each pair of values is summed.

int[] integers1 = new int[] { 1, 2, 3, 4, 5 };
int[] integers2 = new int[] { 10, 20, 30, 40, 50 };
var sumsZip = integers1.Zip(integers2, (i, j) => i + j);

// 11, 22, 33, 44, 55

In the second example we add an array of characters so that we can demonstrate combining sequences of differing types. Here a character and an integer from the source arrays are combined with string.Format to generate a string. Note also that the list of characters is longer than the integer sequence. The final item, "F", is dropped from the results.

char[] characters = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
var items = characters.Zip(integers1, (c, i) => string.Format("{0}{1}", c, i));

// A1, B2, C3, D4, E5
7 May 2011