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?