Merging dictionaries in C#

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

    Note that if you use an extension method called 'Add', you get to use collection initializers to combine as many dictionaries as needed like this:

    public static void Add(this Dictionary d, Dictionary other) {
      foreach (var kvp in other)
      {
        if (!d.ContainsKey(kvp.Key))
        {
          d.Add(kvp.Key, kvp.Value);
        }
      }
    }
    
    
    var s0 = new Dictionary {
      { "A", "X"}
    };
    var s1 = new Dictionary {
      { "A", "X" },
      { "B", "Y" }
    };
    // Combine as many dictionaries and key pairs as needed
    var a = new Dictionary {
      s0, s1, s0, s1, s1, { "C", "Z" }
    };
    

提交回复
热议问题