具有唯一键和值的C#字典类型

A.R*_*.R. 13 c# collections dictionary

我想知道C#中是否有类似"字典"的内置类型,但TKey和TValue都必须是唯一的.

例如::

d.Add(1, "1");
d.Add(2, "1"); // This would not be OK because "1" has already been used as a value.
Run Code Online (Sandbox Code Playgroud)

我知道这有点奇特,但似乎因为BCL中有大约十亿种收藏类型,它可能存在.有任何想法吗?

Ole*_*Dok 15

如何使用Dictionary和HashSet/secondary reverse Dictionary - 它将解决问题,并且比单个Dictionary上的检查表现更好.

像这样的东西,包装为类:

HashSet<string> secondary = new HashSet<string>(/*StringComparer.InvariantCultureIgnoreCase*/);
Dictionary<int, string>dictionary = new Dictionary<int, string>();
object syncer = new object();

public override void Add(int key, string value)
{
  lock(syncer)
  {
    if(dictionary.ContainsKey(key))
    {
      throw new Exception("Key already exists");
    }

    if(secondary.Add(value)
    {
      throw new Exception("Value already exists");
    }
    dictionary.Add(key, value);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 然后将其包装在一个自定义类中。 (2认同)
  • @OlegDok 如果您必须阅读代码超过 1 次 - 绝对是的!(并且您应该总是期望有一天必须再次阅读此代码。) (2认同)