3

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.

Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
Farhad-Taran
  • 6,282
  • 15
  • 67
  • 121

2 Answers2

3

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.

Community
  • 1
  • 1
vlad
  • 4,748
  • 2
  • 30
  • 36
2

Here's another option that is just slightly more compact:

    var keys = dictionaryA.Keys.Where(x => dictionaryB.Keys.Contains(x)).ToArray();
    foreach(var key in keys)
    {
         dictionaryA[key] = dictionaryB[key];
         dictionaryB.Remove(key);
    }
Austin Johnson
  • 135
  • 1
  • 11