具有唯一键和值的 C# 字典类型 [英] C# dictionary type with unique keys and values
本文介绍了具有唯一键和值的 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 中有大约 10 亿个集合类型,所以它可能存在.有什么想法吗?
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?
推荐答案
使用 Dictionary 和 HashSet/secondary reverse Dictionary 怎么样 - 它将解决问题并且比检查单个 Dictionary 的性能更好.
How about having Dictionary and HashSet/secondary reverse Dictionary - it will solve the issue and will perform better than checks on single 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);
}
}
这篇关于具有唯一键和值的 C# 字典类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文