57

Given some Dictionaries

Dictionary<string, string> GroupNames = new Dictionary<string, string>();
Dictionary<string, string> AddedGroupNames = new Dictionary<string, string>();

I am unable to merge them into one:

GroupNames = GroupNames.Concat(AddedGroupNames);

because "the type can't be implicitly converted". I believe (and my code proves me true) their type is the same - what am I overlooking?

Alexander
  • 19,906
  • 19
  • 75
  • 162

1 Answers1

116

I think you defined your GroupNames as Dictionary<string,string>, so you need to add ToDictionary like this:

GroupNames = GroupNames.Concat(AddedGroupNames)
                       .ToDictionary(x=>x.Key,x=>x.Value);

Note that 2 original dictionaries would have different keys, otherwise we need some rule to merge them correctly.

King King
  • 61,710
  • 16
  • 105
  • 130
  • 6
    Great..this is far simpler solution compared to other answers given in the question marked above as original ! – Milind Thakkar Aug 01 '14 at 06:10
  • 7
    It's a good solution, but the only problem it has is about duplicate keys. If there is duplicate keys, an exception would be thrown. – Saeed Neamati Aug 04 '14 at 08:17
  • 6
    If there are duplicate keys, use the following code `GroupNames = GroupNames.Concat(AddedGroupNames.Where( x=> !GroupNames.ContainsKey(x.Key))).ToDictionary(x=>x.Key, x=>x.Value)` – KY Lu Oct 29 '19 at 03:32