C#字典类型具有独特的键和值
问题描述:
我不知道是否有一个内置在C#类型是像'词典',但其中两个TKEY的,并TValue必须是唯一的。
I was wondering if there was a built in type in C# that was like 'Dictionary' but where both TKey and TValue had to be unique.
例如:
d.Add(1, "1");
d.Add(2, "1"); // This would not be OK because "1" has already been used as a value.
我知道这是一种异国情调,但似乎因为有在BCL大约十亿集合类型可能存在。任何想法?
I know this is kind of exotic, but it seems that since there are about a billion collection types in the BCL it might exist. Any ideas?
答
如何有字典和HashSet的/二次反向词典 - 这将解决该问题,并将在单字典进行检查比好
How about having Dictionary and HashSet/secondary reverse Dictionary - it will solve the issue and will perform better than checks on single Dictionary.
这样的事情,包装成类:
Something like this, wrapped as class:
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);
}
}