字典和KeyValuePair

Las*_*son 1 c# collections dictionary

我对词典有疑问,希望你能帮助我.

我有以下声明:

class MainCollection<TKey1, TKey2, TValue> : Dictionary<KeyValuePair<TKey1, TKey2>, TValue>
Run Code Online (Sandbox Code Playgroud)

问题是我无法通过TKey1 TKey2 从这本词典中获取一个元素.有没有办法只通过TKey1或TKey2获得一个元素,而不是TKey1和TKey2?

我写了以下代码:

 public TValue GetItemByKey1(TKey1 key)
 {
     MainCollection<int, int, string> Coll = new MainCollection<int, int, string>();
     var value = from s in Coll where s.Key.Key == key select s.Value;
 }
Run Code Online (Sandbox Code Playgroud)

但它已经有两个问题:

  1. 编译错误:s.Key.Key == key => operator ==不能应用于int和TKey1类型
  2. 它看起来很难看.即使编译成功,我也不确定这是获取此类项目的最快方法.我猜词典应该更好.

我该如何解决这些错误?我在这里找不到任何相关的问题.提前致谢!

jas*_*son 5

好的,所以你希望能够通过TKey1或查找TKey2.然后你想要的是三个词典,每个键一个,然后一个用于键对.

class Foo<TFirstKey, TSecondKey, TValue> {
    private readonly Dictionary<TFirstKey, List<TValue>> firstDictionary
        = new Dictionary<TFirstKey, List<TValue>>();
    private readonly Dictionary<TSecondKey, List<TValue>> secondDictionary
        = new Dictionary<TSecondKey, List<TValue>>();
    private Dictionary<Tuple<TFirstKey, TSecondKey>, TValue> dictionary
        = new Dictionary<Tuple<TFirstKey, TSecondKey>, TValue>();

    public IEnumerable<TValue> GetByFirstKey(TFirstKey firstKey) {
        return this.firstDictionary[firstKey];
    }

    public IEnumerable<TValue> GetBySecondKey(TSecondKey secondKey) {
        return this.secondDictionary[secondKey];
    }

    public TValue GetByKey(TFirstKey firstKey, TSecondKey secondKey) {
        return this.dictionary[Tuple.Create(firstKey, secondKey)];
    }

    public void Add(TFirstKey firstKey, TSecondKey secondKey, TValue value) {
        this.dictionary.Add(Tuple.Create(firstKey, secondKey), value);
        if(this.firstDictionary.Keys.Contains(firstKey)) {
            this.firstDictionary[firstKey].Add(value);
        }
        else {
            this.firstDictionary.Add(firstKey, new List<TValue> { value });
        }
         if(this.secondDictionary.Keys.Contains(secondKey)) {
            this.secondDictionary[secondKey].Add(value);
        }
        else {
            this.secondDictionary.Add(secondKey, new List<TValue> { value });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,只有查找方式(TFirstKey, TSecondKey)是唯一的,因此您需要GetByFirstKeyGetBySecondKey返回集合.

我会把剩下的细节留给你.

关键是如果你想在任一键上快速查找,你需要两个字典(一个用于密钥对的每个坐标).使用一个可以通过查询键集来工作,但这很慢(搜索键是线性的).