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         }
View Code

第二種:

 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         }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM