C#LINQ通过比较键合并字典

时间:2016-12-09 17:19:19

标签: c# dictionary linq-to-entities

我有2个词典,如下所示

Dictionary<string, string> first= new Dictionary<string, string>();
 Dictionary<string, string> second = new Dictionary<string, string>();


first.Add("NAME", "NAME");
first.Add("TYPE", "TYPE");
first.Add("REF","REF");
first.Add("NUMBER", "NUMBER");
first.Add("DATE", "DATE");
first.Add("SOURCE", "SOURCE");

second.Add("TYPE", "T1");
second.Add("REF","A1234");
second.Add("NUMBER", "B456");
second.Add("DATE", "D123455");
second.Add("NAME", "NAME");
second.Add("SOURCE", "SOURCE");

如何实现如下所示的词典

("NAME", "NAME");
("TYPE", "T1");
("REF","A1234");
("NUMBER", "B456");
("DATE", "D123455");
("SOURCE", "SOURCE");

理想情况下,第一个和第二个合并在一起,第二个合并到第一个的值,键应保留在第一个字典的顺序。 任何人都可以建议实现这一目标的最佳方法,谢谢。

1 个答案:

答案 0 :(得分:1)

 var result = first.Union(second)
                   .GroupBy(x => x.Key)
                   .Select(x => new { Key = x.Key, Value = x.Last().Value })
                   .ToDictionary(x => x.Key, x => x.Value);

首先,您将两个集合合并在一起,然后按键选择值Last().Value并再次将其转换为Dictionary

此处Full example