Reputation: 889
I want to update data. From input data converted to same structure from one dictionary into another dictionary, my already existing data.
Pseudo code:
Dictionary<foo, bar> originalData; // Count = 128
Dictionary<foo, bar> inputData; // Count = 112
I could just write the following code:
foreach (var key in originalData.Keys)
{
if (inputData.ContainsKey(key))
{
originalData[key] = inputData[key];
}
}
But of course this will produce the following error:
"Collection was modified; enumeration operation may not execute."
What is the best way to handle this operation?
Upvotes: 1
Views: 110
Reputation: 14017
Your problem is that you are modifying the collection you are iterating. You can use LINQ ToArray
to iterate on a copy of your keys and avoid your problem:
foreach (var key in originalData.Keys.ToArray())
{
if (inputData.ContainsKey(key))
{
originalData[key] = inputData[key];
}
}
Upvotes: 1
Reputation: 727077
You can start from the other end: rather than iterating originalData
, iterate inputData
:
foreach (var pair in inputData) {
if (originalData.ContainsKey(pair.Key)) {
originalData[pair.Key] = pair.Value;
}
}
Note that by iterating key-value pairs you avoid the second look-up into inputData
.
You can go further, and convert if
to LINQ:
foreach (var pair in inputData.Where(p => originalData.ContainsKey(p.Key))) {
originalData[pair.Key] = pair.Value;
}
Upvotes: 3
Reputation: 157136
Why not turn around the iterator? It is safe since you test the keys to exist in both dictionaries.
foreach (var key in inputData.Keys)
{
if (originalData.ContainsKey(key))
{
originalData[key] = inputData[key];
}
}
Upvotes: 3