2

I have two Dictionary<Person,Boolean>. dict a contains :

Person A -> false
Person B -> true,
Person C -> false;

dict b contains :

Person A -> true;
Person D -> false;

I want to have an result, which contains all Persons one time, and set Boolean to ture, if a person contains a true in one of both lists.

How can i solve this with dict.Union() ?

Thanks Kooki

timrau
  • 22,578
  • 4
  • 51
  • 64
Kooki
  • 1,157
  • 9
  • 30
  • http://stackoverflow.com/questions/294138/merging-dictionaries-in-c-sharp – Rob P. Oct 08 '12 at 12:16
  • 1
    _"all Persons one time"_ What makes your person distinct? – Tim Schmelter Oct 08 '12 at 12:17
  • is equality determined by the hash key or by some custom comparison. If it's the hash is this the default implementation (which is semantically a ref comparison, so two identical objects from a value perspective would still be different) or your own implementation? – Rune FS Oct 08 '12 at 12:22
  • Default equality is based on the reference and that seems quite adequate here. – H H Oct 08 '12 at 12:25

1 Answers1

4

Sounds like you could use:

var result = first.Union(second)
                  .GroupBy(x => x.Key)                // Group by dictionary keys
                  .ToDictionary(g => g.Key,           // Key for new dictionary
                                g => g.Any(p => p.Value)); // Any true values?
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194