top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Zip operator in Linq with .NET 4.0

+2 votes
148 views

How to use Zip operator in Linq with .NET 4.0?

posted Mar 6, 2014 by Khusboo

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

The Zip query operator was not included in LINQ initially but was added as an afterthought in .NET 4.0.

It operates on two sequences in parallel, returning another sequence whose elements are the result of applying a method to corresponding pairs of elements from the input sequences.

The name appears to have been chosen because it works a bit like a zipper.

A simple example should help to make it clear how it works.

Suppose you have two arrays of equal length. The first array contains some numbers, the second array contains some names corresponding to those numbers and you'd like to produce an array of strings combining this information.

The following program does that:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
       int[] numbers = {1, 2, 3, 4, 5, 6};
       string[] names = {"Dave", "Jack", "Sam", "Don", "John", "Fred"};
       string[] combined = numbers.Zip(names, (number, name) => number + " : " + name).ToArray();
       foreach(string c in combined) Console.WriteLine(c);
       Console.ReadKey();
    }
}

The output is:

1 : Dave
2 : Jack
3 : Sam
4 : Don
5 : John
6 : Fred

If the input sequences are of unequal length, then the output sequence will have the length of the smaller sequence and the additional elements of the other sequence will be ignored. So, if we change the integer array in the above code to:

int[] numbers = {1, 2, 3, 4, 5, 6, 7};

or we change the string array to:

string[] names = {"Dave", "Jack", "Sam", "Don", "John", "Fred", "Bill"};

then the output will be exactly the same as above.

Source: http://www.c-sharpcorner.com/Blogs/8797/using-linqs-zip-query-operator.aspx

answer Mar 6, 2014 by Salil Agrawal
Similar Questions
+4 votes

How to Generic Method to Create and Execute Parameterized SQL Query in .NET 4.0 ?

+4 votes

How can i create recursive linq (vb.net)?

+4 votes
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...