2010-10-20 79 views
1

我有問題可以從一個字典編輯到另一個字典。編輯C#中另一個字典的字典

Dictionary<string, string> firstDic = new Dictionary<string, string>(); 
firstDic.Add("one", "to make link"); 
firstDic.Add("two", "line break"); 
firstDic.Add("three", "put returns"); 

Dictionary<string, string> secondDic= new Dictionary<string, string>(); 
secondDic.Add("two", "line feeding"); 

// How could I write code something to change firstDic following from secondDic 
// So dictionary firstDic will contain pair data 
// "one" = "to make link" 
// "two" = "line feeding" 
// "three" = "put returns" 
// The code may like 
// firstDict = firstDict.Select(?????????) 

注意。

+0

您可能需要提供更多信息? – RobS 2010-10-20 01:48:07

回答

1

您可以使用下面的代碼全部來自secondDic元素插入firstDic

if (firstDic.ContainsKey(pair.Key)) 
{ 
    firstDic[pair.Key] = pair.Value; 
} 

如果您只想複製這些跨如果鍵已經存在,你可以這樣做檢查正是如此:

foreach (KeyValuePair<string, string> pair in secondDic) 
{ 
    if (firstDic.ContainsKey(pair.Key)) 
    { 
     firstDic[pair.Key] = pair.Value; 
    } 
} 
0

這裏是一個擴展方法,將這樣的伎倆:

public static Dictionary<T,U> Edit<T,U>(this Dictionary<T,U> dictionary1, Dictionary<T,U> dictionary2) { 
    foreach (T key in dictionary2.Keys) 
    { 
     if (dictionary1.ContainsKey(key)) 
     { 
      dictionary1[key] = dictionary2[key]; 
     } 
    } 
    return dictionary1; 
} 
0

LINQ Approch

firstDic = firstDic.ToDictionary(X => X.Key, X => secondDic.ContainsKey(X.Key) ? secondDic[X.Key] : X.Value);