Merging dictionaries in C#

Posted by orip on Stack Overflow See other posts from Stack Overflow or by orip
Published on 2008-11-16T17:39:56Z Indexed on 2010/04/19 17:23 UTC
Read the original article Hit count: 1782

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about dictionary