Free Information Technology Magazines and eBooks

Saturday, June 13, 2009

Combine two sequences using LINQ Zip Operator

Zip is new LINQ to Objects .NET 4.0 Operator that combines the elements from two sequences. It parse the element at the same index position in each sequence until one of the sequences finish reading its elements. Zip operator should be use on two sequence that are identical in length. It takes two arguments, (the element from first source, and the element from the second source) and it returns a combined type.

Here's the signature of the Zip method


public static IEnumerable Zip(
this IEnumerable first,
IEnumerable second,
Func func);


Sample usages of Zip


string[] employee = { "Fryan", "Auric", "James" };
string[] designation = { "Manager", "Programmer", "Designer" };

var emp = employee.Zip(designation, (employee, designation) => employee + " is a " + designation + " of the company.");

foreach (var e in emp)
Console.WriteLine(e);


Results:
Fryan is a Manager of the company.
Auric is a Programmer of the company.
James is a Designer of the company.


For more LINQ tips & tricks, subscribe now.

0 comments: