Try using for-loops to iterate over the collection instead of foreach when you modify objects in the collection you are iterating over.
See Jared Par's code here: [
^]; that thread has a good discussion of different aspects of this problem.
Another strategy that allows you to use a foreach iterator is to build a List in the foreach iterator of objects you wish to modify, and then, after the iteration is complete, modify only those objects by iterating over that List.
A common strategy when
removing items from a Collection using a for-loop is traverse the loop in end-to-front order so that indexes remain meaningful.
Another strategy is to Cast your whatever-you-are-iterating to another List, or even an Array, which lets you use foreach.
Given a Dictionary like this:
Dictionary<string,> dctStrStr = new Dictionary<string,>
{
{"1", "1"},
{"2", "2"},
{"3", "3"},
{"4", "4"},
{"5", "5"},
};
This will fail: collection modified error:
foreach (var theKey in dctStrStr.Keys)
{
dctStrStr[theKey] += " modified";
}
This is okay:
foreach (var theKey in dctStrStr.Keys.ToList())
{
dctStrStr[theKey] += " modified";
}
And this is okay:
foreach (string sKey in dctStrStr.Select(kvp => kvp.Key).ToList())
{
dctStrStr[sKey] += " modified";
}