繁体   English   中英

比较两个词典中的键

[英]Compare Keys in Two Dictionaries

我正在尝试比较两个词典,该程序是用C#Visual Studio 2010编写的。

Dictionary<int, string> members1 = new Dictionaries<int, string>{
    {1, "adam"},
    {2, "bob"},
    {3, "cameron"}
}

Dictionary<int, string> members2 = new Dictionaries<int, string>{
    {1, "adam"},
    {2, "bill"},
    {4, "dave"}
}

我想找到相同的id(密钥),并且名称(值)是否相同无关紧要。

我一直在寻找并发现IntersectExcept ,但我认为它并不像我想要的那样。

通过上面的示例,如果我调用Intersect函数,我希望它返回List<int>{1, 2}

如果我调用members1.Except(members2)类的东西,我希望它返回

Dictionary<int, string> intersectMembers{
    {1, "adam"},
}

我想做的解决方案是编写2个for循环并使用dictionary.Contains(key)来获得我想要的结果。

有没有更直接的方式这样做?

谢谢

如果你想要一个“Common Dictionary ”,我相信你可以这样做:

   var intersectMembers =  members1.Keys.Intersect(members2.Keys)
                                  .ToDictionary(t => t, t => members1[t]);

或者, 或者

   var intersectMembers =  members1.Where(x => members2.ContainsKey(x.Key))
                             .ToDictionary(x => x.Key, x => x.Value);

但是 ,如果您想要返回“公共列表 ”,那么谢尔盖是正确的,您可以实现他的答案。

 var commonKeys = members1.Keys.Intersect(members2.Keys); // { 1, 2 }

这将返回IEnumerable<int>但如果需要列表,可以调用ToList()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM