How do you loop through a multidimensional array?

Don't use foreach - use nested for loops, one for each dimension of the array.

You can get the number of elements in each dimension with the GetLength method.

See Multidimensional Arrays (C# Programming Guide) on MSDN.


Simply use two nested for loops. To get the sizes of the dimensions, you can use GetLength():

for (int i = 0; i < arrayOfMessages.GetLength(0); i++)
{
    for (int j = 0; j < arrayOfMessages.GetLength(1); j++)
    {
        string s = arrayOfMessages[i, j];
        Console.WriteLine(s);
    }
}

This assumes you actually have string[,]. In .Net it's also possible to have multidimensional arrays that aren't indexed from 0. In that case, they have to be represented as Array in C# and you would need to use GetLowerBound() and GetUpperBound() the get the bounds for each dimension.


With a nested for loop:

for (int row = 0; row < arrayOfMessages.GetLength(0); row++)
{
   for (int col = 0; col < arrayOfMessages.GetLength(1); col++)
   {
      string message = arrayOfMessages[row,col];
      // use the message
   }    
}