如何比较具有相同键但不同值的两个Dictionary值?

时间:2020-06-22 15:53:02

标签: c# visual-studio

我有这两个字典,我需要将相同键的值进行比较。

Dict1 = { 1,“蓝色” 2,“黄色” 3,“红色”}

Dict2 = { 1,“红色” 2,“黄色” 3,“红色”}

例如,将值与键1进行比较,然后返回false。但是,当比较时,键2的值将返回true。

2 个答案:

答案 0 :(得分:0)

可能的解决方案:

          Dictionary<int, string> d1 = new Dictionary<int, string>
            {
                {1, "blue"},
                {2, "yellow"},
                {3, "red"},
                {4, "black"}
            };

            Dictionary<int, string> d2 = new Dictionary<int, string>()
            {
                {1, "purple"},
                {2, "yellow"},
                {3, "red"},
                {4, "red"}
            };

            var d3 = d2.Where(x => d1[x.Key] == x.Value)
                 .ToDictionary(x => x.Key, x => x.Value);

答案 1 :(得分:0)

也许您可以尝试使用这些解决方案。在这里,您将找到dict1键,然后在dict2中找到相似的键时,将比较每个字典中该键的值。

Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();

foreach (string k in dict1.Keys){
   if (dict2.ContainsKey(k))
   {
       bool compareValues = (dict1[k] == dict2[k]);
   }
}

希望它能起作用,如果您还有其他问题,请告诉我们!