[英]how to compare two Dictionaries values with same keys but different values?
I have these two dictionaries and I need to compare the values with the same key.我有这两个字典,我需要用相同的键比较值。
Dict1={ 1, "blue" 2, "yellow" 3,"red"} Dict1={ 1, "蓝色" 2, "黄色" 3,"红色"}
Dict2={ 1, "red" 2, "yellow" 3, "red"} Dict2={ 1, “红色” 2, “黄色” 3, “红色”}
for instance, compare the values with key 1 and return false.例如,将值与键 1 进行比较并返回 false。 But when it compares the values of key 2 returns true.但是当它比较键 2 的值时返回 true。
A possible solution:一个可能的解决方案:
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);
Maybe you can try with these solution.也许您可以尝试使用这些解决方案。 Here you go through the dict1 keys, and when you find a similar key in dict2, you compare the values of that key in each dictionary.在这里,您通过 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]);
}
}
Hope it works, tell us if you have another problem!希望它有效,如果您有其他问题,请告诉我们!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.