1

传统词典将包含key-value对。我需要一些东西来保存两种key-key不同类型的对象。例如,key1key2

SourceIdentity key1 = dict[key2]; //key2 index gives key1 value
TargetIdentity key2 = dict[key1]; //key1 index gives key2 value

换句话说,两个键都应该产生另一个值,一种双向访问。我将像其他方式一样添加值:

dict.Add(s, t);

不, key1s 和 key2s 不会有任何重复,因为它们是 keys

这是我能想到的,但我认为可以有一种更轻松的方式:

public class FunnyDictionary
{
  var key1Dict = new Dictionary<SourceIdentity, TargetIdentity>();
  var key2Dict = new Dictionary<TargetIdentity, SourceIdentity>();

  public void Add(SourceIdentity key1, TargetIdentity key2)
  {
      key1Dict[key1] = key2;
      key2Dict[key2] = key1;
  }

  //remaining part..
}

在 c# 中看到过这个问题 Multi-key dictionary?但与我现在的情况完全不同。我想要一本字典,这样我就可以快速访问值,否则我将不得不在每次我觉得可以避免的时候枚举一个集合。该集合将有超过 10000 个条目。这是我能拥有的最轻的吗?以任何其他方式更简单或更好的东西?

4

0 回答 0