1

Dictionary 1:

Dictionary<string, IList<PuntoMappa>> PuntiCantieriCMS = new Dictionary<string, IList<PuntoMappa>>();

Dictionary 2:

Dictionary<string, IList<PuntoMappa>> PuntiCantieri = new Dictionary<string, IList<PuntoMappa>>();

I want Union those both; where the key is the same, they must union IList<PuntoMappa> for each key. Is it possible?

Tried:

PuntiCantieri = PuntiCantieri .Union(PuntiCantieriCMS ).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

but when 2 keys are similar, it trigger an exception.

markzzz
  • 44,504
  • 107
  • 265
  • 458
  • possible duplicate of [Merging dictionaries in C#](http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp) – Sani Singh Huttunen Jun 10 '13 at 13:53
  • 2
    Stop marking this as a duplicate of [Merging dictionaries in C#](http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp). The latter question doesn't care what happens in the case of key collisions, whereas this question clearly states that lists must be merged. – Douglas Jun 10 '13 at 13:57

2 Answers2

4

This should work:

Dictionary<string, List<PuntoMappa>> unioned = PuntiCantieriCMS
        .Concat(PuntiCantieri)
        .GroupBy(kv => kv.Key)
        .ToDictionary(kv => kv.Key, kv => kv.SelectMany(g => g.Value).ToList());

Note that i've changed the value from IList<T> to List<T>.

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • But it returns different type. In fact I can't do `PuntiCantieri = unioned;` after that Linq – markzzz Jun 10 '13 at 14:01
  • @markzzz: If you need the `IList` cast it accordingly: `.ToDictionary(kv => kv.Key, kv => (IList)kv.SelectMany(g => g.Value).ToList());` – Tim Schmelter Jun 10 '13 at 14:02
  • I think because I need `Dictionary>`, not List :O – markzzz Jun 10 '13 at 14:03
  • @markzzz: Yes, have you seen my _note_ ;-) My last comment shows how to cast it to `IList`. – Tim Schmelter Jun 10 '13 at 14:04
  • Why changing `IList` to `List`?? It should work since `List` is an `IList`. – Ahmed KRAIEM Jun 10 '13 at 14:05
  • 2
    @AhmedKRAIEM: No, i assume that's meant with [Covariance and Contravariance](http://msdn.microsoft.com/en-us/library/ee207183.aspx). A `List` is a `IList` implicitely but a `Dictionary>` is not a `Dictionary>`. The compiler doesn't like that. – Tim Schmelter Jun 10 '13 at 14:07
1
 foreach(var kvp in PuntiCantieri)
 {
      if(PuntiCantieriCMS.ContainsKey(kvp.Key))
      {
         kvp.Value.AddRange(PuntiCantieriCMS[kvp.Key]);
      }

 } 
Bill Gregg
  • 6,674
  • 1
  • 18
  • 33