views:

38

answers:

3

I have problem to edit from one dictionary to another dictionary.

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(?????????)

Regard.

+1  A: 

You can insert all the elements from secondDic into firstDic using the following code:

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

If you only want to copy those across if they key already exists, you can do that check thusly:

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

Here's an extension method that will do the trick:

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;
}
Andrew Cooper
+1  A: 

LINQ Approch

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