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.

C#, using GeSHi 1.0.8.8
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6.  
  7. namespace ConsoleApplication1
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string[] a = { "a", "b", "c", "d" };
  14. int[] num = { 1, 2, 3, 4 };
  15. int[] numdiff = { 1, 2, 3, };
  16.  
  17.  
  18. Console.WriteLine("Zip Exmpale with same length");
  19. var ZipResult = a.Zip(num,(ae, ne)=>ae + ", " + ne.ToString());
  20. foreach (string s in ZipResult)
  21. {
  22. Console.WriteLine(s);
  23. }
  24.  
  25. Console.WriteLine("\n\n\nZip Exmpale with diffrent length");
  26. ZipResult = a.Zip(numdiff,(ae, ne)=>ae + ", " + ne.ToString());
  27. foreach (string s in ZipResult)
  28. {
  29. Console.WriteLine(s);
  30. }
  31.  
  32. Console.ReadKey();
  33. }
  34.  
  35. }
  36. }
Parsed in 0.021 seconds at 44.60 KB/s

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
Published Saturday, June 19, 2010 7:51 PM by Jalpesh P. Vadgama

Comments

# Twitter Trackbacks for Zip operator in Linq with .NET 4.0 - DotNetJaps [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Zip operator in Linq with .NET 4.0 - DotNetJaps         [asp.net]        on Topsy.com

# Enumerable#zip特性

Sunday, June 20, 2010 11:59 AM by ASP.NET Chinese Blogs

作者: geff zhang 发表于 2010-06-20 23:29 原文链接 阅读: 16 评论: 0 看到文章 Zip operator in Linq with .NET 4.0 , Enumerable#zip

# re: Zip operator in Linq with .NET 4.0

Wednesday, June 23, 2010 9:36 PM by Surge

this is helpful thanks.

Leave a Comment

(required) 
(required) 
(optional)
(required)