Merging dictionaries in C#

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

    using System.Collections.Generic;
    using System.Linq;
    
    public static class DictionaryExtensions
    {
        public enum MergeKind { SkipDuplicates, OverwriteDuplicates }
        public static void Merge(this IDictionary target, IDictionary source, MergeKind kind = MergeKind.SkipDuplicates) =>
            source.ToList().ForEach(_ => { if (kind == MergeKind.OverwriteDuplicates || !target.ContainsKey(_.Key)) target[_.Key] = _.Value; });
    }
    

    You can either skip/ignore (default) or overwrite the duplicates: And Bob's your uncle provided you are not overly fussy about Linq performance but prefer instead concise maintainable code as I do: in which case you can remove the default MergeKind.SkipDuplicates to enforce a choice for the caller and make the developer cognisant of what the results will be!

提交回复
热议问题