![](/img/trans.png)
[英]How to assign key and values to a dictionary from another dictionary in C#?
[英]Edit dictionary from another dictionary in 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(?????????)
看待。
您可以將所有的元素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;
}
}
這是可以解決問題的擴展方法:
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;
}
LINQ方式
firstDic = firstDic.ToDictionary(X => X.Key, X => secondDic.ContainsKey(X.Key) ? secondDic[X.Key] : X.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.