1

I have a Dictionary that I need to copy, since it is not possible to change a Dictionary in a foreach loop. (Will lead to the error "Collection was modified; enumeration operation may not execute") After I learned

dictTemp.Add(dict);

will just reference one Dictionary to another. I tried to copy it

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But I sill got the error and so I think the Add of the Key and the Value is just a reference. I looked about the problem and found a solution by deep copy with Clone (.Net 2.0). https://stackoverflow.com/a/139841/3772108

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value.Clone());
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But it is not possible in .Net 4.5 because of the message "'int' does not contain a definition for Clone and no extension method Clone accepting a first argument of type 'int' could be found"

Now is my question in the year 2017, how is it possible to COPY a dictionary completely. (Not referencing it) Or is there a smarter/better way?

user3772108
  • 854
  • 2
  • 14
  • 32
  • If you want to copy dictionary (though I doubt you really need to), in 2017 you can use `var copy = dict.ToDictionary(c => c.Key, c => c.Value);` – Evk Nov 16 '17 at 11:03

1 Answers1

4

First, you try to clone an int not the dictionary. You don't need to clone value types, just assign them to the variable and you get a "clone".

Your foreach-loop has also a bug, you check if !dict.ContainsKey instead of !dictTemp.ContainsKey:

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dictTemp.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

Finally, you can use the constructor to get a "clone":

var dictTemp = new Dictionary<string, int>(dict);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thanks for the hint with the bug. I totally overlooked it. The solution with the constructor is just AWESOME! This is exactly I was looking for! Thanks a lot. :) – user3772108 Nov 16 '17 at 12:01