我想知道C#中是否有一个类似“Dictionary”的内置类型,但TKey和TValue必须是唯一的.
例如::
d.Add(1,"1"); d.Add(2,"1"); // This would not be OK because "1" has already been used as a value.
我知道这是一种异国情调,但似乎BCL中有大约十亿种收藏类型可能存在.有任何想法吗?
解决方法@H_404_10@
如何使用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);
}
}
像这样的东西,被包装成类:
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); } }