Merging dictionaries in C#

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

    Got scared to see complex answers, being new to C#.

    Here are some simple answers.
    Merging d1, d2, and so on.. dictionaries and handle any overlapping keys ("b" in below examples):

    Example 1

    {
        // 2 dictionaries,  "b" key is common with different values
    
        var d1 = new Dictionary() { { "a", 10 }, { "b", 21 } };
        var d2 = new Dictionary() { { "c", 30 }, { "b", 22 } };
    
        var result1 = d1.Concat(d2).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.First().Value);
        // result1 is  a=10, b=21, c=30    That is, took the "b" value of the first dictionary
    
        var result2 = d1.Concat(d2).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.Last().Value);
        // result2 is  a=10, b=22, c=30    That is, took the "b" value of the last dictionary
    }
    

    Example 2

    {
        // 3 dictionaries,  "b" key is common with different values
    
        var d1 = new Dictionary() { { "a", 10 }, { "b", 21 } };
        var d2 = new Dictionary() { { "c", 30 }, { "b", 22 } };
        var d3 = new Dictionary() { { "d", 40 }, { "b", 23 } };
    
        var result1 = d1.Concat(d2).Concat(d3).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.First().Value);
        // result1 is  a=10, b=21, c=30, d=40    That is, took the "b" value of the first dictionary
    
        var result2 = d1.Concat(d2).Concat(d3).GroupBy(ele => ele.Key).ToDictionary(ele => ele.Key, ele => ele.Last().Value);
        // result2 is  a=10, b=23, c=30, d=40    That is, took the "b" value of the last dictionary
    }
    

    For more complex scenarios, see other answers.
    Hope that helped.

提交回复
热议问题