【问题标题】:compare dictionaries比较字典
【发布时间】:2012-02-03 18:11:07
【问题描述】:

我有 3 个通用词典

static void Main(string[] args)
{
    Dictionary<string, string> input = new Dictionary<string, string>();
    input.Add("KEY1", "Key1");

    Dictionary<string, string> compare = new Dictionary<string, string>();
    compare.Add("KEY1", "Key1");
    compare.Add("KEY2", "Key2");
    compare.Add("KEY3", "Key3");

    Dictionary<string, string> results = new Dictionary<string, string>();

我想获取输入列表并将每个值与 compareTo 列表进行比较,如果不存在则将其添加到结果列表中?

【问题讨论】:

  • 澄清一下,您希望compare 中的所有成员而不是input 中的所有成员?或者input 的所有成员不在compare 中?我假设前者,但如果后者只是在我的答案中反转操作数。
  • 这个问题有点含糊。您想将每个值与compare 列表进行比较,但什么是值?您的意思是input.Values 中的string 项目之一是否存在于compare.Values 中,或者input 中的KeyValuePair&lt;string, string&gt; 项目之一是否存在于compare 中?或者您只是在查看键,正如人们在使用字典的代码中所期望的那样?
  • @phoog:我从他在问题中的“比较每个值”中假设他想要任何不同或不存在的值(对于给定键)在结果中。那是正确的杆吗?

标签: c#


【解决方案1】:

您可以使用 LINQ except() 方法:

        foreach (var pair in compare.Except(input))
        {
            results[pair.Key] = pair.Value;
        }

这将执行一组差异(实际上是从 compare 中减去 input 并返回剩余的内容),然后我们可以将其添加到 results 字典中。

现在,如果 results 没有以前的值,而您只希望它是当前操作中的 results,您可以直接这样做:

      var results = compare.Except(input)
                           .ToDictionary(pair => pair.Key, pair => pair.Value);

这是假设您想要键 值的差异。如果您有不同的值(相同的键),它会显示在差异中。

也就是说,对于您的示例,上面的结果将具有:

[KEY2, Key2]
[KEY3, Key3]

但如果您的示例数据是:

        Dictionary<string, string> input = new Dictionary<string, string>();
        input.Add("KEY1", "Key1");

        Dictionary<string, string> compare = new Dictionary<string, string>();
        compare.Add("KEY1", "X");
        compare.Add("KEY2", "Key2");
        compare.Add("KEY3", "Key3");

结果是:

[KEY1, X]
[KEY2, Key2]
[KEY3, Key3]

由于KEY1的值不同。

如果您只想要另一个不包含键或值的地方,您可以在字典的KeysValues 集合上执行Except

【讨论】:

  • 我认为你把它弄反了。如果我理解正确的话是input.Except(compare)
  • @Cicada:我认为他想要compare 中的所有元素,而不是input 中的所有元素。如果他显然想要相反的结果,他只会反转操作数。
【解决方案2】:

dict[key] 为您提供键为 key 的值。

dict.ContainsKey(key)dict.ContainsValue(value) 是可用于检查键或值是否在字典中的方法。 ContainsKey 更省时。

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多