.NET 4.0 LINQ Operator – Zip

.NET 4.0 includes the new extension method Zip with the Enumerable, ParallelEnumerable, and Queryable classes. Zip allows to merge two sequences. Other LINQ operators that merge two sequences are Union, Intersect, Join, and GroupJoin. These operators have been available since .NET 3.5.

Zip that is available with .NET 4 and can be compared to the Join operator. Instead of the keys that are used Zip just uses the order of the elements to combine elements from two sequences. Zip creates one element from two elements taken from two input sequences. How the elements are merged depends on a result selector function, and the elements can be of different types. This makes the declaration of the Zip method simpler.

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)

With Zip it’s for example possible to sum two the elements of two integer sequences by passing the Lambda expression (first, second) => first + second to the result selector. This creates the result values 8, 15, 22, 26 in the following code snippet.

int[] one = { 3, 7, 11, 14 };
int[] two = { 5, 8, 11, 12 };

var result1 = one.Zip(two, (first, second) => first + second);

Of course it’s possible to do anything in the selector method. The next code snippet returns the lower value of the two collections – 3, 7, 11, 12. You can also combine sequences of different types and return another type. That all just depends on the selector method.

Via http://weblogs.thinktecture.com/cnagel/2010/02/linq-with-net-4-zip.html


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s