Loop Multiple Arrays in C# – Short way

Let us see a trick to loop multiple arrays in C#. Consider the following program:

static void Main(string[] args)
var arr1 = new[] { 5, 3, 4, 2, 6, 7 };
var arr2 = new[] { 4, 9, 3, 1, 9, 4 };
var arr3 = new[] { 2, 1, 8, 7, 4, 9 };

foreach (int num in arr1)

foreach (int num1 in arr2)

foreach (int num2 in arr3)


static void Print(int i)

As you can see, we are using three loops to print the contents of the array. Using the LINQ Concat operator, we can shorten the code by reducing three loops into just one, as shown below

If you liked this tip, check some more LINQ Tips

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: