[英]How to get values from dictionary with composite keys?
我的程序有一个单元格网格,我希望能够按行或按列号有效地查询。 我应该使用哪种结构来做到这一点?
例如,我想使用以下方法:
CellsCollection.GetCell(Int32 row, Int32 column)
CellsCollection.GetAllCellsInRow(Int32 row)
CellsCollection.GetAllCellsInColumn(Int32 column)
我的第一个尝试是创建一个具有两个字段(行和列)的结构,然后创建一个具有该结构的复合键的Dictionary<struct, cell>
: 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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.