簡體   English   中英

如何比較具有相同鍵但不同值的兩個字典值?

[英]how to compare two Dictionaries values with same keys but different values?

我有這兩個字典,我需要用相同的鍵比較值。

Dict1={ 1, "藍色" 2, "黃色" 3,"紅色"}

Dict2={ 1, “紅色” 2, “黃色” 3, “紅色”}

例如,將值與鍵 1 進行比較並返回 false。 但是當它比較鍵 2 的值時返回 true。

一個可能的解決方案:

          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);

也許您可以嘗試使用這些解決方案。 在這里,您通過 dict1 鍵 go,當您在 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]);
   }
}

希望它有效,如果您有其他問題,請告訴我們!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM