使用foreach循环将值循环到二维数组中

本文关键字:循环 二维数组 foreach 使用 | 更新日期: 2023-09-27 18:19:30

所以我尝试使用foreach将值循环到二维数组中。我知道代码应该是这样的。

        int calc = 0;
        int[,] userfields = new int[3,3];
        foreach (int userinput in userfields)
        {
            Console.Write("Number {0}: ", calc);
            calc++;
            userfields[] = Convert.ToInt32(Console.ReadLine());
        }

这是我所能做到的。我试过使用

userfields[calc,0] = Convert.ToInt32(Console.ReadLine());

但显然这对二维数组不起作用。我对C#还比较陌生,我正在努力学习,所以我很感激所有的答案。

提前感谢!

使用foreach循环将值循环到二维数组中

它是一个二维数组,顾名思义,它有两个维度。因此,当您想要分配一个值时,您需要指定两个索引。类似:

// set second column of first row to value 2
userfield[0,1] = 2; 

在这种情况下,您可能想要一个for循环:

for(int i = 0; i < userfield.GetLength(0); i++)
{
    for(int j = 0; j < userfield.GetLength(1); j++)
    {
       //TODO: validate the user input before parsing the integer
       userfields[i,j] = Convert.ToInt32(Console.ReadLine());
    }
}

有关更多信息,请查看:

  • 多维数组(C#编程指南)