DotNetStories
In this rather short post I will be demonstrating with a
hands-on example the usefulness of the
Linq Zip operator.
You can find more information on Linq expressions and operators (both in query and method syntax) in this post.
I am going to use Visual Studio 2012 Ultimate edition (Visual Studio 2012 Express for Web edition) and I will create an ASP.Net 4.0 Web forms application
I can use LINQ queries not only against databases but against arrays, since the array of strings/integers implement the IENumerable interface.
Just to be absolutely clear you can query any form of data
that implements the IENumerable interface.
The Zip operator merges the corresponding elements of two sequences using a specified selector function.
The Zip query operator was not included in LINQ. It was added later in .NET 4.0.
1) Fire up Visual Studio 2012.
2) Create an empty web site. Give it the name of your
choice.Choose C# as the
development language.
3) Add a web form item to your site. Leave the default name.
We will have two string arrays. One array will consist of football teams and another one will consist of their football nicknames.
We will merge those two arrays.
4) In the Page_Load event handling
routine type
protected void Page_Load(object sender, EventArgs e) { string[] footballteamnames = { "Manchester United", "Liverpool", "Arsenal", "Aston Villa" }; string[] footballnicknames = { "Red Devils", "The Reds", "Gunners", "Villagers"}; var teamswithnicknames = footballteamnames.Zip (footballnicknames,(team, nickname) => team + " - " + nickname); foreach ( var item in teamswithnicknames ) { Response.Write(item); Response.Write("<br/>"); } }
We declare two string arrays footballteamnames and footballnicknames. We will match the football names with the nicknames.
We declare a variable teamswithnicknames and then we
call the Zip operator on the first list,passing in
the name of the second list. Then we have a lambda
expression declaring how we want the lists zipped
together.
So we say that we want the second array to be zipped with
the first one and then we indicate through the delegate how
they should be combined.
Build and run your application. You will see the following
results.
Manchester United - Red Devils
Liverpool - The Reds
Arsenal - Gunners
Aston Villa - Villagers
Hope it helps!!!!