2

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.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Tronics
  • 1,438
  • 4
  • 22
  • 33
  • 2
    `var keys = rmDict.Keys.Concat(vaDict.Keys).Concat(smDict.Keys).Distinct();` – Dmitry Bychenko Apr 08 '21 at 14:47
  • Does this answer your question? [Get unique items from multiple lists using LINQ- C#](https://stackoverflow.com/questions/29104244/get-unique-items-from-multiple-lists-using-linq-c-sharp) – Self Apr 08 '21 at 14:50
  • https://stackoverflow.com/questions/26201952/selecting-distinct-elements-from-two-lists-using-linq/26201980 – Self Apr 08 '21 at 14:52

2 Answers2

5

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);
 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
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);
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69