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



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: