Merging dictionaries in C#

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

    or :

    public static IDictionary Merge( IDictionary x, IDictionary y)
        {
            return x
                .Except(x.Join(y, z => z.Key, z => z.Key, (a, b) => a))
                .Concat(y)
                .ToDictionary(z => z.Key, z => z.Value);
        }
    

    the result is a union where for duplicate entries "y" wins.

提交回复
热议问题