在C#合并Dictonaries使用LINQ [英] Merging Dictonaries in C# using LINQ
问题描述
我已经3 Dictonaries像
i've three Dictonaries like
Dictionary<int,List<string>> D1 = new Dictionary<int,List<string>>();
Dictionary<int,List<string>> D2= new Dictionary<int,List<string>>();
Dictionary<int,List<string>> D3 new Dictionary<int,List<string>>();
D1[1] = new List<string>{"a","b"};
D1[2] = new List<string>{"c","d"};
D1[3] = new List<string>{"e","f"};
D1[4] = new List<string>{"h"};
D2[1] = new List<string>{"a","b"};
D2[2] = new List<string>{"c","d"};
D2[3] = new List<string>{"e","f"};
D2[4] = new List<string>{"g"};
D2[5] = new List<string>{"b","h"};
D2[6] = new List<string>{"f","l"};
D2[7] = new List<string>{"z"};
我需要两个dictonary合并成一个单一的dictonary
i need to merge the two dictonary into a single dictonary
像
D3[1] = {"a","b","h"}
D3[2] = {"c","d"}
D3[3] = {"e","f","l"}
合并规则:
D1 [1] = {一,b}这列表将与在D 2
D1[1]={"a","b"} this list will be compared with the values in the D2
D2 [1] = {一,b}
D2[1]={"a","b"}
D2 [5] = {b,H}
D2[5]={"b","h"}
所以上述三个将被合并到
so the above three will be merged into
D3 [1] = {一,b,H}
D3[1]={"a","b","h"}
有任何想法做此使用LINQ
is there any idea to do this using LINQ
推荐答案
不过是你要合并的值,你可能会想使用这些选项之一:
However are you trying to merge the values, you will probably want to use one of these options:
D3[1] = D1[1].Union(D2[1]);
或
D3[1] = D1[1].Concat(D2[1]);
修改 - 用于加入了一个难看的方法合并Linq的风格:
Edit - an ugly-looking method for joined merges Linq-style:
foreach (var kvp in D1)
{
D3[kvp.Key] =
(from string letter in kvp.Value
select
(from IEnumerable<string> list in D2.Values
where list.Contains(letter)
select list)
// Union all the D2 lists containing a letter from D1.
.Aggregate((aggregated, next) => aggregated.Union(next)))
// Union all the D2 lists containing all the letter from D1.
.Aggregate((aggregated, next) => aggregated.Union(next))
// Convert the unioned letters to a List.
.ToList();
}
代码保持在D2名单,这将是很容易修改代码从D2删除匹配的列表。
The code keeps the lists in D2, it would be pretty easy to modify the code to remove the matched lists from D2.
这篇关于在C#合并Dictonaries使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!