如何使用复合键从字典中获取值
本文关键字:获取 字典 何使用 复合 | 更新日期: 2023-09-27 18:00:22
我的程序有一个单元格网格,我希望能够有效地按行或按列编号进行查询。我应该用什么样的结构来做这件事?
例如,我希望有以下方法:
CellsCollection.GetCell(Int32 row, Int32 column)
CellsCollection.GetAllCellsInRow(Int32 row)
CellsCollection.GetAllCellsInColumn(Int32 column)
我的第一次尝试是创建一个包含两个字段(行和列)的结构,然后创建一个具有结构的复合键的字典:Dictionary<struct, cell>
。
CellsCollection.GetCell(Int32 row, Int32 column)
没有问题,因为我将通过复合键查询字典。
另外两个(在行/列中获取单元格)出现了问题,因为如果我这样做:
dictionary.Where(keyPair=>keyPair.Key.Row == row).Select(keyPair=>keyPair.Values.Cell)
然后字典中的键变得没有意义,程序必须遍历字典中的每个键。
我想到了一个嵌套字典(外部有行键,内部有列键),但只有按行而不是按列查询时,这才有帮助。
你将如何克服这一点?
如果索引中有空白,字典就很好。如果你有一个单元格网格,那么我猜情况并非如此(除非你有很多空单元格)。
那么,为什么不有一个二维数组呢?例如
int[,] cells = new int[maxRow,maxColumn];
这样,如果你想查询特定的单元格,你只需进行
int cellValue = cells[row,column]
或
public int GetCell(Int32 row, Int32 column)
{
return cells[row, column]
}
如果你想把所有东西都排成一排:
for(int col = 0; col < maxColumn; col++)
int cellValue = cells[row, col];
或
public IEnumerable<int> GetAllCellsInRow(Int32 row)
{
for(int col = 0; col < maxColumn; col++)
yeldReturn cells[row, col];
}
对于类似的列中的所有内容
for(int row = 0; row < maxRow; row++)
int cellValue = cells[row, column];
或
public IEnumerable<int> GetAllCellsInColumn(Int32 column)
{
for(int row = 0; row < maxRow; row++)
yield return cells[row, column];
}