How do you loop through a multidimensional array?

后端 未结 7 1358
陌清茗
陌清茗 2021-01-03 19:50
foreach (String s in arrayOfMessages)
{
    System.Console.WriteLine(s);
}

string[,] arrayOfMessages is being passed in as a parameter

7条回答
  •  执笔经年
    2021-01-03 20:23

    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.

提交回复
热议问题