使用嵌套的 Foreach 语句迭代多维数组 [英] Iterate Multi-Dimensional Array with Nested Foreach Statement

查看:33
本文介绍了使用嵌套的 Foreach 语句迭代多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这可能是一个非常简单的问题,但我还没有弄清楚.如果我有一个像这样的二维数组:

I think this might be a pretty simple question, but I haven't been able to figure it out yet. If I've got a 2-dimensional array like so:

int[,] array = new int[2,3] { {1, 2, 3}, {4, 5, 6} };

使用嵌套的 foreach 语句遍历数组的每个维度的最佳方法是什么?

What's the best way to iterate through each dimension of the array with a nested foreach statement?

推荐答案

如果你想遍历数组中的每一项,就好像它是一个扁平数组,你可以这样做:

If you want to iterate over every item in the array as if it were a flattened array, you can just do:

foreach (int i in array) {
    Console.Write(i);
}

哪个会打印

123456

如果您还想知道 x 和 y 索引,则需要执行以下操作:

If you want to be able to know the x and y indexes as well, you'll need to do:

for (int x = 0; x < array.GetLength(0); x += 1) {
    for (int y = 0; y < array.GetLength(1); y += 1) {
        Console.Write(array[x, y]);
    }
}

或者,您可以使用锯齿状数组代替(数组数组):

Alternatively you could use a jagged array instead (an array of arrays):

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
    for (int k = 0; k < array[j].Length; k += 1) {
        Console.Write(array[j][k]);
    }
}

这篇关于使用嵌套的 Foreach 语句迭代多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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