2011-06-26 45 views
0

我的程序有一個單元格網格,我希望能夠按行或按列號高效查詢。我應該用什麼樣的結構來做到這一點?如何使用複合鍵從字典中獲取值?

比如我想有以下幾種方法:

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) 

然後辭典鍵將失去意義,程序要經過字典中的每一個關鍵。

我想到了一個嵌套的字典(外部的一個行鍵和內部的一個列鍵),但我只會幫助,如果我按行查詢,而不是列。

你會如何克服這一點?

回答

3

如果您的索引中存在空白,字典是非常好的。如果你有一個單元格網格,那麼我猜測情況並非如此(除非你有很多空單元格)。因此,爲什麼不有一個二維數組?例如

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

這是如此瘋狂,它只是可能會奏效!現在如何處理需要調整數組的大小,因爲需要更多的行/列? (爲了以防萬一,我不能只分配最大數量的行和列)。 – Manuel

+0

我用字典和數組測試了這兩個數組,並且數組更快並且使用更少的內存。 – Manuel

相關問題