使用嵌套foreach语句迭代多维数组 [英] Iterate Multi-Dimensional Array with Nested Foreach Statement
本文介绍了使用嵌套foreach语句迭代多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我觉得这可能是一个pretty简单的问题,但我一直没能弄明白呢。如果我有一个2维数组,像这样:
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 语句?
推荐答案
如果你想每一个项目遍历数组中,好像它是一个扁平的数组,你可以做:
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屋!
查看全文