C#C
C#4y ago
57 replies
Hercules

❔ How do you merging Dictionaries into one Dictionary?

Has anyone merged two dictionaries of same type into one?
I read something like this


var result = dictionaries.SelectMany(dict => dict)
                         .ToLookup(pair => pair.Key, pair => pair.Value)
                         .ToDictionary(group => group.Key, group => group.First());


Lookup(https://learn.microsoft.com/en-us/dotnet/api/system.linq.lookup-2?view=net-7.0).

But will this code make the dictionary distinct (that values and keys don't repeat). I rather use same key and add the value from the dictionary i'm merging/joining.

Maybe this option makes it ignore
new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
Represents a collection of keys each mapped to one or more values.
Lookup Class (System.Linq)
Was this page helpful?