Reputation: 1490
I have three dictionaries with same type keys. I need to get distinct keys for all three dictionaries. How can I do that?
var rmDict = rmTrxs
.GroupBy(x => new { x.Name, x.Pfx.Id })
.ToDictionary(z => z.Key, z => z.ToList());
var vaDict = vaTrxs
.GroupBy(x => new { x.Name, x.Pfx.Id })
.ToDictionary(z => z.Key, z => z.ToList());
var smDict = smTrxs
.GroupBy(x => new { x.Name, x.Pfx.Id })
.ToDictionary(z => z.Key, z => z.ToList());
Now I need to get distinct keys from rmDict
, vaDict
and smDict
.
Upvotes: 2
Views: 257
Reputation: 186843
I understand you right, you can Concat
all the keys and then get rid of duplicates with a help of Distinct
:
using System.Linq;
...
var distinctKeys = rmDict
.Keys
.Concat(vaDict.Keys)
.Concat(smDict.Keys)
.Distinct();
For non Linq solution, you can use HashSet<T>
:
//TODO: put the right type instead of MyType
var distinctKeys = new HashSet<MyType>(rmDict.Keys);
distinctKeys.UnionWith(vaDict.Keys);
distinctKeys.UnionWith(smDict.Keys);
Upvotes: 5
Reputation: 6917
var d1 = new Dictionary<int, string>{
{1, "one"},
{3, "three"},
{5, "five"},
};
var d2 = new Dictionary<int, string>{
{1, "one"},
{2, "two"},
{3, "three"},
};
var d3 = new Dictionary<int, string>{
{2, "two"},
{4, "four"},
{6, "six"},
};
var dictionaries = new List<Dictionary<int, string>>{
d1, d2, d3
};
var final = dictionaries.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(group => group.Key, group => group.First());
Console.WriteLine(final);
Upvotes: 0