Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0

Assuming we have multiple sequences as follows containing different set of elements :

var bldgNum = new string[] {"A5", "A2", "A1" };
var flatNum = new int[] {104, 109, 25, 200 };
var streetNm = new string[] {"Baker Street", "Cross Street", "Hu Street" };
var city = new string[] { "CO", "WA", "AU", "CA" };

To merge the elements of all these sequences, use the Zip operator that is new in .NET Framework 4.0

“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”

static void CombineSeq()
{
var bldgNum = new string[] {"A5", "A2", "A1" };
var flatNum = new int[] {104, 109, 25, 200 };
var streetNm = new string[] {"Baker Street", "Cross Street", "Hu Street" };
var city = new string[] { "CO", "WA", "AU", "CA" };

var address = bldgNum
.Zip(flatNum, (bl, fl) => bl + ", " + fl.ToString())
.Zip(streetNm, (fl, st) => fl + " , " + st)
.Zip(city, (st, ct) => st + ", " + ct);

foreach (var addr in address)
Console.WriteLine(addr);

}

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: