Merging dictionaries in C#

前端 未结 26 1286
温柔的废话
温柔的废话 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条回答
  •  孤独总比滥情好
    2020-11-22 09:00

    A version from @user166390 answer with an added IEqualityComparer parameter to allow for case insensitive key comparison.

        public static T MergeLeft(this T me, params Dictionary[] others)
            where T : Dictionary, new()
        {
            return me.MergeLeft(me.Comparer, others);
        }
    
        public static T MergeLeft(this T me, IEqualityComparer comparer, params Dictionary[] others)
            where T : Dictionary, new()
        {
            T newMap = Activator.CreateInstance(typeof(T), new object[] { comparer }) as T;
    
            foreach (Dictionary 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;
        }
    

提交回复
热议问题