Showing posts with label NETFramework4. Show all posts
Showing posts with label NETFramework4. Show all posts
Saturday, June 19, 2010

Zip operator in Linq with .NET 4.0

Microsoft .NET framework 4.0 is having many features that make developers life very easy. Its also provides some enhancement to Linq also. I just found a great operator called Zip which merge the sequence of two entities.

Here is the explanation of Zip Operator from MSDN.

“The method merges each element of the first sequence with an element that has the same index in the second sequence. If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them”.

Here is the simple console application for the zip. I have taken three arrays for that one is string array, second one is integer array which is having same length as string array and third one is also integer array but having different length then string array. Here is the sample code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] a = { "a", "b", "c", "d" };
int[] num = { 1, 2, 3, 4 };
int[] numdiff = { 1, 2, 3, };


Console.WriteLine("Zip Exmpale with same length");
var ZipResult = a.Zip(num,(ae, ne)=>ae + ", " + ne.ToString());
foreach (string s in ZipResult)
{
Console.WriteLine(s);
}

Console.WriteLine(@"\n\n\nZip Exmpale with diffrent length");
ZipResult = a.Zip(numdiff,(ae, ne)=>ae + ", " + ne.ToString());
foreach (string s in ZipResult)
{
Console.WriteLine(s);
}

Console.ReadKey();
}

}
}
Here is the output of following code as expected.Linq Zip Operator in .NET 4.0

Hope this will help you.

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews