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)
归档时间: |
|
查看次数: |
14304 次 |
最近记录: |