C# 程序循环遍历二维数组
csharpprogrammingserver side programming更新于 2025/9/17 0:44:00
声明一个二维数组 −
string[,] array = new string[3, 3];
设置数组中的元素 −
array[0, 0] = "One"; array[0, 1] = "Two"; array[0, 2] = "Three"; array[1, 0] = "Four"; array[1, 1] = "Five"; array[1, 2] = "Six"; array[2, 0] = "Seven"; array[2, 1] = "Eight"; array[2, 2] = "Nine";
现在,获取上界,以获取循环遍历数组的维度 −
int uBound0 = array.GetUpperBound(0); int uBound1 = array.GetUpperBound(1);
通过嵌套循环进行迭代,直到得到上述两个值,如下面的代码所示 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
string[,] array = new string[3, 3];
array[0, 0] = "One";
array[0, 1] = "Two";
array[0, 2] = "Three";
array[1, 0] = "Four";
array[1, 1] = "Five";
array[1, 2] = "Six";
array[2, 0] = "Seven";
array[2, 1] = "Eight";
array[2, 2] = "Nine";
// 获取上限
int uBound0 = array.GetUpperBound(0);
int uBound1 = array.GetUpperBound(1);
for (int i = 0; i <= uBound0; i++) {
for (int j = 0; j <= uBound1; j++) {
string res = array[i, j];
Console.WriteLine(res);
}
}
Console.ReadLine();
}
}
输出
One Two Three Four Five Six Seven Eight Nine

