d2=newDic"/> d2=newDic">

首页  >  文章  >  后端开发  >  如何在 C# 中比较两个字典?

如何在 C# 中比较两个字典?

王林
王林转载
2023-09-14 10:49:021073浏览

如何在 C# 中比较两个字典?

要比较两个字典,首先设置两个字典 -

字典一

IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);

// Dictionary One elements
Console.WriteLine("Dictionary One elements: "+d.Count);

字典一

IDictionary<int, int> d2 = new Dictionary<int, int>();
d2.Add(1,97);
d2.Add(2,89);
d2.Add(3,77);
d2.Add(4,88);

// Dictionary Two elements
Console.WriteLine("Dictionary Two elements: "+d2.Count);

现在让我们比较它们 -

bool equal = false;
if (d.Count == d2.Count) { // Require equal count.
   equal = true;
   foreach (var pair in d) {
      int value;
      if (d2.TryGetValue(pair.Key, out value)) {
         if (value != pair.Value) {
            equal = false;
            break;
         }
      } else {
         equal = false;
         break;
      }
   }
}

上面比较了两个词典。现在打印控制台,结果将为 True。这意味着两个字典具有相同的值。

以上是如何在 C# 中比较两个字典?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除