如果我有一个字典,每个键可以拥有多个值(即 Dictionary < string , Hashset < string >>
),现在我想检查 dic [key a] 的哈希集合中是否包含一个名为“b”的值,怎么做呢?
如果我有一个字典,每个键可以拥有多个值(即 Dictionary < string , Hashset < string >>
),现在我想检查 dic [key a] 的哈希集合中是否包含一个名为“b”的值,怎么做呢?
我认为测试存在的最有效方法是,如果结构和检查函数定义如下:
// extension method on IDictionary<TKey, HashSet<TValue>> can be used
public static bool ContainsKeyValue<TKey, TValue>(IDictionary<TKey, HashSet<TValue>> dictOfHash, TKey key, TValue value)
{
if (!dictOfHash.ContainsKey(key))
return false;
return dictOfHash[key].Contains(value);
}
var dict = new Dictionary<int, HashSet<String>>()
{
{ 1, new HashSet<String>() { "one", "two", "three"} },
{ 2, new HashSet<String>() { "ten", "eleven", "twelve"} }
};
bool exists = ContainsKeyValue(dict, 1, "two");
exists = ContainsKeyValue(dict, 1, null);
exists = ContainsKeyValue(dict, 2, "one");
exists = ContainsKeyValue(dict, 3, null);
存在性检查应该具有O(1)的复杂度,因为Dictionary<,>
和Hashset<>
都具有O(1)的获取/设置复杂度。
public static bool Contains<Tkey, TValue>(this Dictionary<Tkey, IEnumerable<TValue>> dic, Tkey key, TValue val)
{
if (dic.ContainsKey(key))
return dic[key].Contains(val);
return false;
}
尝试使用 IDictionary<>.TryGetValue
,它可以节省一次表查找:
public static bool Contains<TKey, TValue>(this IDictionary<TKey, HashSet<TValue>> dictionary, TKey key, TValue value)
{
var hashSet;
if(dictionary.TryGetValue(key, out hashSet))
{
return hashSet.Contains(value);
}
else
{
return false;
}
}