LINQ:合并字典 [英] Linq: Merge the dictionaries
问题描述
我在C#两本词典。
两个字典及其calues是
The Two Dictionaries and their calues are
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"};
其中1,2,3和4词典D1的键
Where 1,2,3 and 4 are keys of Dictionary D1
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"};
其中1,2,3,4,5,6和7词典D2的键
Where 1,2,3,4,5,6 and 7 are keys of Dictionary D2
然后输出字典包含此值,
Then the output Dictionary Contains this values,
D3[1] = {"a","b","h"} D3[2] = {"c","d"} D3[3] = {"e","f","l"}
请注意:请把字典输入比1.Thats值大于为什么我消除了D1 [4],D2 [ 4]和D2 [7]
Note: Please take the Input Dictionary with values greater than 1.Thats why i am eliminating the D1[4] , D2[4] and D2[7]
是否有可能将其合并使用LINQ?
IS IT POSSIBLE TO MERGE IT USING LINQ?
推荐答案
是的,它是可能的,但它并不漂亮!
Yes it's possible but it's not pretty!
//firstly lets get the keys that are valid (i.e. have more than one element in their list)
var validD1Elements = D1.Where(d => d.Value.Count > 1);
var validD2Elements = D2.Where(d => d.Value.Count > 1);
//merge the valid keys together so we know which ones we want to select
var mergedKeys = validD1Elements.Select(d => d.Key).Union(validD2Elements.Select(d => d.Key));
//perform the merge
var mergeResult = mergedKeys.Select (key => new
{
Key = key,
//select the values from D1
Value = validD1Elements.Where(d => d.Key == key).SelectMany(d => d.Value)
//concat the values from D2
.Concat(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))
}).ToDictionary(e => e.Key, e => e.Value);
本合并使用的毗连所以你会得到重复,即 mergeResult [1]
将 {A,b,A,b}
。
This merge uses Concat so you will get duplicates, i.e. mergeResult[1]
will be { "a", "b", "a", "b" }
.
如果你不想重复这一更改下面的代码:
If you do not want duplicates change the following code from this:
//concat the values from D2
.Concat(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))
这样:
//union the values from D2
.Union(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))
mergeResult [1]
,然后将 {A,b}
。
这篇关于LINQ:合并字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!