密钥对字典,双向访问密钥?

时间:2013-03-28 11:12:22

标签: c# dictionary key-value

传统词典将保留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中的任何重复项,因为它们是键

这是我能想到的,但我认为可以采用更轻松的方式:

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..
}

我已经看到了这个问题Multi-key dictionary in c#?,但现在没有我的情况了。 我想要一本字典,以便我可以快速访问值,否则我每次都要枚举一个集合,我觉得可以避免。该集合将有超过10000个条目。 这是我能拥有的最轻的吗?以其他方式更简单或更好的东西?

0 个答案:

没有答案
相关问题