如何在C#中比较两个字典 [英] How to compare two Dictionaries in C#
问题描述
我有两个通用词典.两者具有相同的键,但它们的值可以不同.我想比较第二本字典和第一本字典.如果它们的值之间存在差异,我想将这些值存储在单独的字典中.
I have two generic Dictionaries. Both have the same keys, but their values can be different. I want to compare the 2nd dictionary with the 1st dictionary. If there are differences between their values, I want to store those values in a separate dictionary.
1st Dictionary
------------
key Value
Barcode 1234566666
Price 20.00
2nd Dictionary
--------------
key Value
Barcode 1234566666
Price 40.00
3rd Dictionary
--------------
key Value
Price 40
谁能给我最好的算法来做到这一点?我写了一个算法,但它有很多循环.我正在寻找一个简短而有效的想法,例如使用 LINQ 查询表达式或 LINQ lambda 表达式的解决方案.我在 C# 中使用 .NET Framework 3.5.我发现了一些关于 Except()
方法的信息,但不幸的是我无法理解该方法发生了什么.如果有人可以解释建议的算法,那就太好了.
Can anyone give me the best algorithm to do this? I wrote an algorithm but it has a lot of loops. I am seeking a short and efficient idea, like a solution using LINQ query expressions or LINQ lambda expressions. I am using .NET Framework 3.5 with C#. I found something about the Except()
method, but unfortunately I couldn't understand what is happening on that method. It would be great if anyone could explain the suggested algorithm.
推荐答案
如果您已经检查过密钥是否相同,则可以使用:
If you've already checked that the keys are the same, you can just use:
var dict3 = dict2.Where(entry => dict1[entry.Key] != entry.Value)
.ToDictionary(entry => entry.Key, entry => entry.Value);
解释一下,这将:
- 迭代
dict2
中的键/值对 - 对于每个条目,在
dict1
中查找值并过滤掉任何两个值相同的条目 - 通过从每一对中取出键和值,就像它们出现在
dict2
中一样,从剩余的条目(即dict1
值不同的条目)形成一个字典.
- Iterate over the key/value pairs in
dict2
- For each entry, look up the value in
dict1
and filter out any entries where the two values are the same - Form a dictionary from the remaining entries (i.e. the ones where the
dict1
value is different) by taking the key and value from each pair just as they appear indict2
.
请注意,这避免了依赖 KeyValuePair
- 依赖它可能没问题,但我个人觉得这更清楚.(当您为字典键使用自定义相等比较器时,它也可以工作 - 尽管您也需要将其传递给 ToDictionary
.)
Note that this avoids relying on the equality of KeyValuePair<TKey, TValue>
- it might be okay to rely on that, but personally I find this clearer. (It will also work when you're using a custom equality comparer for the dictionary keys - although you'd need to pass that to ToDictionary
, too.)
这篇关于如何在C#中比较两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!