Concatenate two Dictionaries

Alexander picture Alexander · Nov 22, 2013 · Viewed 55.5k times · Source

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?

Answer

King King picture King King · Nov 22, 2013

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.