如何使用复合键从字典中获取值?

时间:2011-06-26 22:44:31

标签: c# .net dictionary

我的程序有一个单元格网格,我希望能够按行或列号有效地查询。我应该用什么样的结构来做这件事?

例如,我想要有以下方法:

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)

然后字典键变得没有实际意义,程序必须遍历字典中的每个键。

我想到了一个嵌套字典(外部字典有一个行键而内部字典有一个列键)但是我只会在按行而不是列查询时才会有用。

你怎么克服这个?

1 个答案:

答案 0 :(得分:3)

如果索引中存在间隙,则字典很棒。如果你有一个单元网格,那么我猜测那不是这种情况(除非你有很多空单元格)。

那么,为什么不拥有二维数组呢? e.g。

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];
}