C#程序循环遍历二维数组

声明一个二维数组-

string[,] array = new string[33];

在数组中设置元素-

array[00] = "One";

array[01] = "Two";

array[02] = "Three";

array[10] = "Four";

array[11] = "Five";

array[12] = "Six";

array[20] = "Seven";

array[21] = "Eight";

array[22] = "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[33];

      array[00] = "One";

      array[01] = "Two";

      array[02] = "Three";

      array[10] = "Four";

      array[11] = "Five";

      array[12] = "Six";

      array[20] = "Seven";

      array[21] = "Eight";

      array[22] = "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

以上是 C#程序循环遍历二维数组 的全部内容, 来源链接: utcz.com/z/321751.html

回到顶部