C# 如何迭代多维数组的行和列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/832655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I iterate rows and columns of a multidimensional array?
提问by Michael Hedgpeth
I would like to iterate the rows and columns separately on a two dimensional array:
我想在二维数组上分别迭代行和列:
object[,] values;
How would I iterate through just the rows and just the columns?
我将如何仅遍历行和列?
采纳答案by Anzurio
It depends what's columns and rows for you but you could use this snippet of code:
这取决于您的列和行,但您可以使用以下代码片段:
for (int i = 0; i < values.GetLength(0); i++)
Console.WriteLine(values[i, 0]);
And:
和:
for (int i = 0; i < values.GetLength(1); i++)
Console.WriteLine(values[0, i]);
回答by Tal Pressman
Multi-dimensional arrays don't have rows and columns in the way you're referring to them - they just have several indexes used to access values. Iterating over such an array would be done using nested for-loops, and if you want to perform certain calculations on a per-dimension base you should alter the order of the loops accordingly.
多维数组没有您所指的行和列——它们只有几个用于访问值的索引。迭代这样的数组将使用嵌套的 for 循环来完成,如果你想在每维基础上执行某些计算,你应该相应地改变循环的顺序。
Another option, if you only need to iterate over one dimension, is to use an array of arrays instead of a multi-dimensional array like this:
另一种选择,如果您只需要迭代一维,则使用数组数组而不是像这样的多维数组:
object[][] values;
回答by JerSchneid
Here's some code to iterate through the first and second dimensions of the array a 2 dimensional array. (There aren't really "rows" and "columns" because a multidimensional array can have any number of dimensions)
这是一些代码,用于遍历数组的第一维和第二维二维数组。(没有真正的“行”和“列”,因为多维数组可以有任意数量的维度)
object[,] values = new object[5,5];
int rowIWant = 3; //Make sure this is less than values.GetLength(0);
//Look at one "row"
for(int i = 0; i < values.GetLength(1); i++
{
//Do something here with values[rowIWant, i];
}
int columnIWant = 2; //Make sure this is less than values.GetLength(1);
//Look at one "column"
for(int i = 0; i < values.GetLength(0); i++
{
//Do something here values[i, columnIWant];
}