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
This topic was copied from this blog at DevCurry, by Suprotim Agarwal.
Carsten Siemens edited Revision 5. Comment: Pirated Content - see my comment
XAML guy edited Revision 4. Comment: tweak
XAML guy edited Revision 3. Comment: added source, do you have permission for this?
Ed Price - MSFT edited Revision 1. Comment: Title casing. Adding tags.
NOTE: This article was reported as Pirated/Plagiarized Content (content you didn't write) and will be removed. Please do not steal content from others. If you feel we are mistaken, please leave a comment or email tnwiki at Microsoft with a link to this article and with clear and detailed reasons why you own the content or have explicit permission from the author.
Content was taken from: "Combine Multiple Sequences in LINQ using the Zip Operator - .NET 4.0"
Published by Suprotim Agarwal on May 04, 2010
www.devcurry.com/.../combine-multiple-sequences-in-linq.html