d2=newDic"/> d2=newDic">

首頁  >  文章  >  後端開發  >  如何在 C# 比較兩個字典?

如何在 C# 比較兩個字典?

王林
王林轉載
2023-09-14 10:49:021076瀏覽

如何在 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刪除