Zip: New LINQ extensions series

Zip is part of .NET 3.1. Since .NET 6 is released recently, it is a good opportunity to mention some of the new LINQ extensions methods. I will post a series of small articles focused on some these new or maybe less known LINQ methods.

In this article I am going to take Zip LINQ method with some examples so it is easier to understand it.

Prerequisites

To to use these new LINQ extensions you need to download and install this version of .NET 6.

I download and install Visual Studio 2022 in this article.

Zip

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

Example

Let take this input as example, we have winners names, the rank and the points in seperate list, but with the right order:

string[] winners = { "John", "Peter", "Mick" };
int[] rank = { 1, 3, 2 };
int[] points = { 99, 95, 96 };

Lets zip them together:

IEnumerable<(string winner, int rank, int point)> zipped = winners.Zip(rank, points);

Now if we can order it for example by rank as one list, and print the results:

foreach (var tuple in zipped.OrderBy(e => e.rank))
{
    Console.WriteLine($"{tuple.rank} {tuple.winner} {tuple.point}");
}

The output will be:

1 John 99
2 Mick 96
3 Peter 95

Download my examples form GitHub.

Microsoft Zip documentation

Leave a Comment