C#合并两个Dictionary的方法
直接代码:
1 public Dictionary<string, string> MergeDictionary(Dictionary<string, string> first, Dictionary<string, string> second) 2 { 3 if (first == null) first = new Dictionary<string, string>(); 4 if (second == null) return first; 5 6 foreach (var item in second) 7 { 8 if (!first.ContainsKey(item.Key)) 9 first.Add(item.Key, item.Value); 10 } 11 12 return first; 13 }
第二种:
1 public Dictionary<string, string> MergeDictionary(Dictionary<string, string> first, Dictionary<string, string> second) 2 { 3 if (first == null) first = new Dictionary<string, string>(); 4 if (second == null) return first; 5 6 //相对于第一种只是修改了遍历的方法 7 foreach (string key in second.Keys) 8 { 9 if (!first.ContainsKey(key)) 10 first.Add(key,second[key]); 11 } 12 return first; 13 }