如何检查字典中的某个键是否包含一个值?

3

如果我有一个字典,每个键可以拥有多个值(即 Dictionary < string , Hashset < string >>),现在我想检查 dic [key a] 的哈希集合中是否包含一个名为“b”的值,怎么做呢?

3个回答

3

我认为测试存在的最有效方法是,如果结构和检查函数定义如下:

// 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)的获取/设置复杂度。


2
您可以使用扩展方法。
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;
}

抱歉,我想我忘记添加了,在 dic[a] 的哈希集合中搜索该字符串 b。由于我的值是一个字符串而不是字符串的哈希集合,所以这段代码将抛出错误。 - brokleyscoding
我无法理解你的意思,请您重新表达一下? - Hamid Pourjam
1
不,很抱歉它起作用了。我一开始没有看到“可枚举”。谢谢。 - brokleyscoding
如果答案解决了你的问题,请不要忘记将其标记为解决方案。 - Starceaker

1

尝试使用 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;
    }         
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接