Merging dictionaries in C#

前端 未结 26 1070
温柔的废话
温柔的废话 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 08:54

    The party's pretty much dead now, but here's an "improved" version of user166390 that made its way into my extension library. Apart from some details, I added a delegate to calculate the merged value.

    /// 
    /// Merges a dictionary against an array of other dictionaries.
    /// 
    /// The type of the resulting dictionary.
    /// The type of the key in the resulting dictionary.
    /// The type of the value in the resulting dictionary.
    /// The source dictionary.
    /// A delegate returning the merged value. (Parameters in order: The current key, The current value, The previous value)
    /// Dictionaries to merge against.
    /// The merged dictionary.
    public static TResult MergeLeft(
        this TResult source,
        Func mergeBehavior,
        params IDictionary[] mergers)
        where TResult : IDictionary, new()
    {
        var result = new TResult();
        var sources = new List> { source }
            .Concat(mergers);
    
        foreach (var kv in sources.SelectMany(src => src))
        {
            TValue previousValue;
            result.TryGetValue(kv.Key, out previousValue);
            result[kv.Key] = mergeBehavior(kv.Key, kv.Value, previousValue);
        }
    
        return result;
    }
    

提交回复
热议问题