Linq: Merge the dictionaries
I have two dictionaries in c#.
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"};
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"};
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"} 开发者_Python百科 D3[3] = {"e","f","l"}
Note: Please take the Input Dictionary with values greater than 1.Thats why i am eliminating the D1[4] , D2[4] and D2[7]
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);
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))
to this:
//union the values from D2
.Union(validD2Elements.Where(d => d.Key == key).SelectMany(d => d.Value))
mergeResult[1]
will then be { "a", "b" }
.
Concat them all, then group by (ToLookup) the key, then union all the values in a grouping, finally shove them all back in a dictionary.
精彩评论