小弟是搞java的  最近闲  看看c#
才看到二维数组 就把我难住了。。
很囧
问题是如何遍历二维数组
比如 int[,] ary = new int[3,4];
如何用for循环遍历呢?又如何用foreach遍历?
不能用i<3当作条件。。orz

解决方案 »

  1.   

    应该是
    for(int i=0;i<3;i++)
       for(int j=0;j<4;j++)
           {}foreach int i in ary
       {}
      

  2.   

    这两种方法都能遍历啊int i = 0, j = 0;
    for(i=0;i<3;i++)
    {
      for(j=0;j<4,j++)
      {
         MessageBox.Show(ary[i,j].ToString());
      }
    }foreach(int num in ary)
    {
      MessageBox.Show(num.ToString());
    }
      

  3.   

    不用i<3做条件
    可以用i<ary.GetLength(0) //取第0维的长度
    相对应的j<ary.GetLength(1)
      

  4.   


                string s = null;
                int[,] ary = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 0, 11, 12 } };          
                for (int i = 0; i < ary.GetLength(0); i++)
                {
                    for (int j = 0; j < ary.GetLength(1); j++)
                    {                     s+= Convert.ToString(ary[i, j]);
                        return s;
                    }
                }
      

  5.   

     //foreach(int ARow in ary)
       //{
       //    Console.WriteLine("{0}\t", ARow);
       //}
      

  6.   

                            int count = 0;
    foreach(int i in arr2)
    {
    Console.Write(i+"\t");
    count++;
    if(count % arr2.GetLength(1) == 0)
    {
    Console.WriteLine();
    }
    }