0

我有一个排序字典:

static SortedDictionary<string, int> myDictionary = new SortedDictionary<string, int>();

其中键代表类似这样的字符串:

string key = someNumber + " " + row + " " + col + " " + someString;

我想要的是找到排序字典中具有特定行和列的所有项目。例如,如果我有以下键:

1 2 3 p 
3 2 3 p 
2 2 3 t 
5 1 6 p 
8 2 1 p 
7 2 3 t

我只想获取这些具有 row=2 和 col=3 的键:

1 2 3 p 
3 2 3 p 
2 2 3 t 
7 2 3 t
4

1 回答 1

3

不幸的是,在这种情况下,您需要遍历整个集合并选择符合您的条件的项目(因此没有太多使用字典本身):

public IList<int> FindValues(int row, int col)
{
    myDictionary
        .Where(item => MatchKey(item.Key, row, col))
        .Select(item => item.Value)
        .ToList();
}

public bool MatchKey(string key, int row, int col)
{
    var splitKey = key.Split();
    return splitKey[1] == row.ToString() && splitKey[2] == col.ToString();
    // or match the key according to your logic
}

虽然如果您需要经常按行和列查询,那么最好先构建不同的数据结构。也许

Dictionary<Coord, IList<int>> myDict;

其中 Coord 是一个类/结构(并覆盖 Equals、GetHashCode)

class Coord
{
    public int Row { get; set; }
    public int Column { get; set; }
}
于 2012-12-15T13:31:41.343 回答