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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: