如何遍历多维数组? [英] How do you loop through a multidimensional array?

查看:29
本文介绍了如何遍历多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆