Merging dictionaries in C#

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

    Option 1 : This depends on what you want to happen if you are sure that you don't have duplicate key in both dictionaries. than you could do:

    var result = dictionary1.Union(dictionary2).ToDictionary(k => k.Key, v => v.Value)
    

    Note : This will throw error if you get any duplicate keys in dictionaries.

    Option 2 : If you can have duplicate key then you'll have to handle duplicate key with the using of where clause.

    var result = dictionary1.Union(dictionary2.Where(k => !dictionary1.ContainsKey(k.Key))).ToDictionary(k => k.Key, v => v.Value)
    

    Note : It will not get duplicate key. if there will be any duplicate key than it will get dictionary1's key.

    Option 3 : If you want to use ToLookup. then you will get a lookup which can have multiple values per key. You could convert that lookup to a dictionary:

    var result = dictionaries.SelectMany(dict => dict)
                             .ToLookup(pair => pair.Key, pair => pair.Value)
                             .ToDictionary(group => group.Key, group => group.First());
    
    0 讨论(0)
  • 2020-11-22 09:17

    Merging using an extension method. It does not throw exception when there are duplicate keys, but replaces those keys with keys from the second dictionary.

    internal static class DictionaryExtensions
    {
        public static Dictionary<T1, T2> Merge<T1, T2>(this Dictionary<T1, T2> first, Dictionary<T1, T2> second)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
    
            var merged = new Dictionary<T1, T2>();
            first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
            second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
    
            return merged;
        }
    }
    

    Usage:

    Dictionary<string, string> merged = first.Merge(second);
    
    0 讨论(0)
提交回复
热议问题