比较两个字典并将结果存储在另一个

本文关键字:结果 存储 另一个 字典 两个 比较 | 更新日期: 2023-09-27 18:01:45

如何比较两本字典,我的字典如下

  Dictionary<string, string> dic = new Dictionary<string, string>();
  dic.Add("One", "One");
  dic.Add("Two", "Two");
  Dictionary<string, string> dic1 = new Dictionary<string, string>();
  dic1 .Add("One", "One");
  dic1 .Add("Two", "Two");
  dic1 .Add("Three", "Three");

我尝试了一些像var diff = dic1.Where(x => x.Value != dic[x.Key]).ToDictionary(x => x.Key, x => x.Value);的东西,但是我得到了异常,因为键不匹配,所以有人能帮助我吗

比较两个字典并将结果存储在另一个

这会给你区别,

var resultDic = dic1.Except(dic).ToDictionary(x => x.Key, x => x.Value);
    private void Comparer(Dictionary<string, string> dic, Dictionary<string, string> dic1)
    {
        var diff = dic.Except(dic1).Concat(dic1.Except(dic));
    }