如何比较在C#两个字典 [英] How to compare two Dictionaries in C#

查看:1214
本文介绍了如何比较在C#两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通用Dictionaries.Both具有相同keys.But值可以是different.I想比较第二字典,词典1号。如果有值之间的差异,我想保存在单独的字典这些值。

I have two Generic Dictionaries.Both have same keys.But values can be different.I want to compare 2nd dictionary with 1st dictionary .If there are differences between values i want to store those values in 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

任何一个可以给我一个最好的算法来干这事写一个算法,但它有很多loops.I的正在寻求一个高效短idea.Also像一个解决方案,通过使用LINQ查询EX pression或LINQ LAMDA EX pression.I正在使用.NET Framework 3.5,C#。我发现了一些东西约除()方法。但不幸的是我不明白发生了什么事上method.It是巨大的,如果任何一个解释建议algorithm.I总是喜欢学习:)

Can Any one give me a best algorithm to do this.I wrote an algorithm but it have lot of loops.I am seeking a short and efficient idea.Also like a solution by using LINQ query expression or LINQ lamda expression.I am Using .Net Framework 3.5 with C#. I found some thing about Except() method .But Unfortunately i couldn't understand what is happening on that method.It is great if any one explains the suggested algorithm.I always like to learn:).

谢谢 萨波。

推荐答案

如果你已经检查过的密钥是相同的,你可以使用:

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 并过滤掉任何条目,其中所述两个值是相同的
  • 一份来自其余条目字典(即那些其中 dict1 值是不同的)通过从每对键和值,就像它们出现在 dict2
  • 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 in dict2.

请注意,这避免了依靠 KeyValuePair&LT的平等; TKEY的,TValue> - 它的也许的没事依靠这一点,但我个人觉得这更清楚。 (当你使用一个自定义相等比较的字典键还将工作 - 尽管你需要传递到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆