【问题标题】:Checking all entries from one Dictionary are in another Dictionary检查一个字典中的所有条目都在另一个字典中
【发布时间】:2016-03-31 09:07:28
【问题描述】:

我有两个字典 A 和 B,我想看看 A 中的所有条目是否都存在于 B 中。过去我使用以下方法比较了列表:

var set1 = new HashSet<String>(list1);
var set2 = new HashSet<String>(list2);

return set1.SetEquals(set2);

我想做的只是简单地循环使用字典 A 中的每个值:

dictA.TryGetValue(dictBvalue, out item)

如果值不存在,这将在 item var 上返回 null,但这似乎有点冗长。

有没有快速有效的比较字典的方法?

谢谢。

【问题讨论】:

    标签: c# compare


    【解决方案1】:

    您可以使用All 扩展名并执行此操作。

    var allexist = list1.All(x=> list2.ContainsKey(x.Key) && list2[x.Key] == x.Value)
    

    【讨论】:

    • 错别字,应该是x :-)
    • 这可以快速有效地满足我的需求,谢谢 :)
    • 澄清一下,如果 list1 中的所有项目都在 list2 中,则返回 true,如果 list1 中的任何项目未出现在 list2 中,则返回 false?
    • 谢谢 :) 再问一个问题,是否可以使用与上述相同的简单方法将 list1 中未在 list2 中找到的键输出到新列表?
    • 使用 list1.Keys.Where(k=&gt;!list2.ContainsKey(k)).ToList() 这会返回 list1 中的键,而 list2 中没有。
    【解决方案2】:

    如果你想遍历每个值,这里是解决方案

    Dictionary<string, string> dictA = new Dictionary<string, string>();
    Dictionary<string, string> dictB = new Dictionary<string, string>();
    bool allexist = true;
    
    foreach (var itemA in dictA)
    {
        if (!dictB.ContainsKey(itemA.Key))
        {
            allexist = false;
        }
    }
    

    【讨论】:

    【解决方案3】:

    实际上,您要求比较字典的方法,但您的代码示例引用了不同的 HashSet。

    对于 HashSet,您可以使用 IsSubsetOfSetEquals 方法。

    要比较字典,可以使用DictionaryEquals method from this answer

    【讨论】:

    • 这只是我将如何处理列表的一个示例,在这种情况下,我正在为字典寻找类似的解决方案。我会检查那个链接,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多