Merging dictionaries in C#

前端 未结 26 1308
温柔的废话
温柔的废话 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:03

    @Tim: Should be a comment, but comments don't allow for code editing.

    Dictionary t1 = new Dictionary();
    t1.Add("a", "aaa");
    Dictionary t2 = new Dictionary();
    t2.Add("b", "bee");
    Dictionary t3 = new Dictionary();
    t3.Add("c", "cee");
    t3.Add("d", "dee");
    t3.Add("b", "bee");
    Dictionary merged = t1.MergeLeft(t2, t2, t3);
    

    Note: I applied the modification by @ANeves to the solution by @Andrew Orsich, so the MergeLeft looks like this now:

    public static Dictionary MergeLeft(this Dictionary me, params IDictionary[] others)
        {
            var newMap = new Dictionary(me, me.Comparer);
            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;
        }
    

提交回复
热议问题