What's the best way to merge 2 or more dictionaries (Dictionary<T1,T2>
) in C#?
(3.0 features like LINQ are fine).
I'm thinking of a method signature along the lines of:
public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);
or
public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);
EDIT: Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.
@Tim: Should be a comment, but comments don't allow for code editing.
Note: I applied the modification by @ANeves to the solution by @Andrew Orsich, so the MergeLeft looks like this now:
Got scared to see complex answers, being new to C#.
Here are some simple answers.
Merging d1, d2, and so on.. dictionaries and handle any overlapping keys ("b" in below examples):
Example 1
Example 2
For more complex scenarios, see other answers.
Hope that helped.