Rewrite Nested ForEach Loop in LINQ

Let’s assume you have two string array's of the same length and you need to loop through each element of the array and concatenate it’s elements. One way to do this is to use nested foreach loops as shown below

string[] uCase = { "A", "B", "C" };
string[] lCase = { "a", "b", "c" };

foreach (string s1 in uCase)
{
foreach (string s2 in lCase)
{
Console.WriteLine(s1 + s2);
}
}

Now if you want to get the same results in LINQ without using a nested foreach, use the IEnumerable.SelectMany which projects each element of a sequence and flattens the resulting sequences into one sequence

string[] uCase = { "A", "B", "C" };
string[] lCase = { "a", "b", "c" };

var ul = uCase.SelectMany(
uc => lCase, (uc, lc) => (uc + lc));

foreach (string s in ul)
{
Console.WriteLine(s);
}

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.

2 comments:

Dave said...

Don't do this. Use the Zip method instead, e.g.:

foreach(var pair in uCase.Zip(lCase, (u, l) => u + l + " ")) {
Console.WriteLine(pair);
}

Suprotim Agarwal said...

Nice alternate approach. Thanks!