如何遍历多维数组? [英] How do you loop through a multidimensional array?
问题描述
foreach (String s in arrayOfMessages)
{
System.Console.WriteLine(s);
}
string[,] arrayOfMessages
作为参数传入.
我希望能够确定哪些字符串来自 arrayOfMessages[0,i]
和 arrayOfMessages[n,i]
,其中 n
是数组的最终索引.
I want to be able to determine which strings are from arrayOfMessages[0,i]
and arrayOfMessages[n,i]
, where n
is the final index of the array.
推荐答案
只需使用两个嵌套的 for
循环.要获取维度的大小,您可以使用 GetLength()
:
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);
}
}
这假设您实际上有 string[,]
.在 .Net 中,也可能有不从 0 开始索引的多维数组.在这种情况下,它们必须在 C# 中表示为 Array
并且您需要使用 GetLowerBound()
和 GetUpperBound()
获取每个维度的边界.
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.
这篇关于如何遍历多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!