TheDeveloperBlog.com


C# Zip Method

Zip. The Zip extension method acts upon two collections. It processes each element in two series together. With a Func instance, we use Zip to handle elements from two C# collections in parallel.

Extension MethodFunc

Example. In this program, we declare two arrays of five integer elements each. Then, we invoke the Zip method. The first argument to the Zip method is the secondary array we want to process in parallel.

Int Array

And: The second argument to the Zip method is a lambda expression that describes a Func instance.

Arguments: Two integer parameters are the arguments to the Func, and the return value is the two parameters added together.

IntReturn
C# program that uses Zip extension method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Two source arrays.
	var array1 = new int[] { 1, 2, 3, 4, 5 };
	var array2 = new int[] { 6, 7, 8, 9, 10 };

	// Add elements at each position together.
	var zip = array1.Zip(array2, (a, b) => (a + b));

	// Look at results.
	foreach (var value in zip)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

7
9
11
13
15

In this example, the Func expression is processed over all five elements of both arrays. The result value is each of the two arrays with their parallel elements added together—a zipped-up array.

Uneven source data? If you happen to have two collections with an unequal number of elements, the Zip method will only continue to the shortest index where both elements exist. No errors will occur if the two collections are uneven.

Tip: Zip will not throw an exception if the two collections are of unequal length.


Summary. The Zip extension method provides a way for you to process two collections or series in parallel. This can replace a lot of for-loops where the index variable is necessary to process two arrays at once.

For