Merging dictionaries in C#

前端 未结 26 1320
温柔的废话
温柔的废话 2020-11-22 08:25

What\'s the best way to merge 2 or more dictionaries (Dictionary) in C#? (3.0 features like LINQ are fine).

I\'m thinking of a method signa

26条回答
  •  Happy的楠姐
    2020-11-22 09:06

    This doesn't explode if there are multiple keys ("righter" keys replace "lefter" keys), can merge a number of dictionaries (if desired) and preserves the type (with the restriction that it requires a meaningful default public constructor):

    public static class DictionaryExtensions
    {
        // Works in C#3/VS2008:
        // Returns a new dictionary of this ... others merged leftward.
        // Keeps the type of 'this', which must be default-instantiable.
        // Example: 
        //   result = map.MergeLeft(other1, other2, ...)
        public static T MergeLeft(this T me, params IDictionary[] others)
            where T : IDictionary, new()
        {
            T newMap = new T();
            foreach (IDictionary src in
                (new List> { me }).Concat(others)) {
                // ^-- echk. Not quite there type-system.
                foreach (KeyValuePair p in src) {
                    newMap[p.Key] = p.Value;
                }
            }
            return newMap;
        }
    
    }
    

提交回复
热议问题