对于数组中的每个元素,我需要一个唯一标识符,例如 Seat1、Seat2、Seat 3......一直到数组长度的末尾。
目前我做了以下几件事:
int rows = 10, cols = 10;
bool[ , ] seatArray = new bool[rows , cols]; //10 rows, 10 collums
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++ )
{
seatArray[i, j] = false;
}
foreach (bool element in seatArray)
{
Console.WriteLine("element {0}", element);
}
}
这只是在控制台中显示“Element False”x 100。
我需要将“Element”替换为 Seat1、Seat2、Seat3……到数组长度的末尾。
任何帮助将不胜感激!
谢谢!
最佳答案
创建一个带有 ID 和 Occupied(?) 属性的 Seat 类(或结构,如果更合适的话)。制作一个这种类型的数组。
public class Seat
{
public string ID { get; set; }
public bool Occupied { get; set; }
}
int rows = 10, cols = 10;
Seat[,] seats = new Seat[rows,cols];
for (int i = 0; i < rows; ++i )
{
for (int j = 0; j < cols; ++j)
{
seats[i,j] = new Seat { ID = "Seat" + (i*cols + j), Occupied = false };
}
}
foreach (var seat in seats)
{
Console.WriteLine( "{0} is{1} occupied", seat.ID, seat.Occupied ? "" : " not" );
}
关于c# - 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4521431/