C# 使用foreach循环将值循环到二维数组中?
所以我尝试使用foreach将值循环到二维数组中。我知道代码应该是这样的C# 使用foreach循环将值循环到二维数组中?,c#,arrays,foreach,console.readline,C#,Arrays,Foreach,Console.readline,所以我尝试使用foreach将值循环到二维数组中。我知道代码应该是这样的 int calc = 0; int[,] userfields = new int[3,3]; foreach (int userinput in userfields) { Console.Write("Number {0}: ", calc); calc++; userfields
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#方面的新手,我正在努力学习,所以我很欣赏所有的答案
提前谢谢 它是一个二维数组,顾名思义,它有两个维度。因此,当您想要赋值时,需要指定两个索引。比如:
// 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());
}
}
for(inti=0;i
有关更多信息,请查看:
// 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());
}
}
for(inti=0;i
有关更多信息,请查看: