Click here to Skip to main content
16,021,687 members
Please Sign up or sign in to vote.
1.00/5 (1 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
C#
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

You can iterate through the array like this,

C#
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[^]
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900