简体   繁体   English

如何迭代多维数组的行和列?

[英]How do I iterate rows and columns of a multidimensional array?

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? 我如何只遍历行和列?

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]);

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];
}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM