Click here to Skip to main content
14,427,124 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi All,

What would be the best way to iterate through a multidimensional array in c#.

I have defined my array as
new string[,,] { { { "A", "B", "C" }, { "D", "E", "F" } } }


But I am having trouble getting my head around the process of a foreach loop.

I want to be able to pass this array as a variable then assign each value as it iterates through the array.

Thanks in advance.
Posted
Comments
Sergey Alexandrovich Kryukov 21-Jul-14 11:23am
   
"...Having trouble getting my head around" is not informative.
—SA

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

You can iterate through the array like this,

string[,,] arr = new string[,,] { { { "A", "B", "C" }, { "D", "E", "F" } } };

           foreach(string k in arr)
           {
               System.Console.Write("{0} ", k);
           }


But MSDN recommends to use nested for loops with multidimensional arrays

"with multidimensional arrays, using a nested for loop gives you more control over the array elements."

Read these posts,

http://msdn.microsoft.com/en-us/library/2h3zzhdw.aspx[^]

http://stackoverflow.com/questions/2834233/how-to-foreach-through-a-2-dimensional-array[^]

http://stackoverflow.com/questions/2834233/how-to-foreach-through-a-2-dimensional-array[^]
   
Comments
Rob Philpott 21-Jul-14 11:25am
   
Nice, couldn't be simpler really.
Dilan Shaminda 21-Jul-14 11:49am
   
Thank you sir :-)
Member 10111284 22-Jul-14 3:35am
   
Thanks for your responses , this is very helpful and should help me get my head around this.
Dilan Shaminda 22-Jul-14 3:40am
   
you are welcome :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100