C# Zip Method

LINQ (language integrated query)

You want to use the Zip extension method. This allows you to act upon each element in two series together. You can process two C# collections together, element by element, in parallel.

This C# tutorial shows how to use the Zip method from System.Linq.

Example

Note

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. The second argument to the Zip method is a lambda expression that describes a Func instance—two integer parameters a and b are the arguments to it, and the return value is the two parameters added together.

Program that uses Zip extension method [C#]

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

Results of the program. The Func expression is processed over all five element indexes of both arrays. The result value is each of the two arrays with their parallel elements added together.

Question and answer

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.

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.

LINQ Examples
.NET