replace values of key value pair(A) with values of matching keys in key value pair(B)?

c#, dictionary

Solution

Not sure where Ani's answer went, but here's a similar solution:

foreach (var k in A.Keys.ToList())
{
    if (B.ContainsKey(k))
    {
        A[k] = B[k];
        B.Remove(k);
    }
}

edit it looks like the original code throws an `InvalidOperationException` when going through the `foreach` loop, thinking that the collection is modified. see this question for details. `ToList()` is required.

Problem

I have 2 dictionaries(key value pair objects) in C#. I want to compare dictionaries A with B and do the following for any keys that are in both dictionaries: 1. Replace the value in dictionary A with the value in dictionary B 2. Remove the matching key from dictionary B An example would be as follows: Initial dictionaries: ``` A={" Key1:value1 "," Key2:value2 "} B={" Key3:bla "," key1:hello "," Key4:bla "," Key2:world "} ``` Afterward: ``` A={" Key1:hello "," Key2:world "} B={" Key3:bla "," Key4:bla "} ``` I would like to know the best way to do this, I'm sure this can be achieved in LINQ but I am still just a beginner, any help is greatly appreciated.

Original source

Related problems