From this answer:
foreach (var key in dict.Keys.ToList())
{
dict[key] = false;
}
The call to ToList() makes this work, since it's pulling out and (temporarily) saving the list of keys, so the iteration works.
Why is the call to ToList()
necessary here?
We're modifying values, not keys, and, to my best understanding, only modyfying the set of keys of a dictionary would break iteration over keys. In particular - to my, likely wrong understanding - the ordering of keys can only change if we are adding or removing items from a dictionary, which we are not doing.