Hello everyone,
I want to iterator a Dictionary variable instance, and remove all elements under a specific condition.
Here is my code. My questions about whether the following solution will function correctly?
1. will dic.Remove(key) operation impact keys collection?
2. will dic.Remove(key) operation impact dic[key] operation?
I have such concern is because I heard while interation in the middle, remove any elements inside the Dictionary is dangerous because it will make some reference invalid and impact result. Any ideas?
[Code]
Dictionary
foreach (string key in keys)
{
// order is a public property of Foo class
if (dic[key].order > 100)
{
// will keys collection variable be impacted if we remove here?
// will dic[key] operation also be impacted?
dic.Remove(key);
}
}
[/Code]
thanks in advance,
George
George GeorgePosted May 19, 2008, 7:00 AM
Thanks Dipal,
I agree with your solution. I have a further question, why my code dic.Remove(key) will invalid the loop foreach (string key in keys)? How Dictinoary is designed which will be impacted?
regards,
George
Dipal ChoksiPosted May 19, 2008, 2:50 AM
George GeorgePosted May 18, 2008, 3:19 AM
Thanks Mike,
In my original code, I am not foreach the whole Dictionary, just the .Keys of the Dictionary (i.e. using Keys Enumerator, not using Dictionary as a whole Enumerator). In this case, deleting an element will also invaliding the Keys Enumerator? Why?
(Does it because .Keys operations on the Dictionary will prefetch all the pointers to old positions before element removal?)
regards,
George
Mike GoldPosted May 18, 2008, 12:28 AM
not sure what will happen, but what you could do is make a copy of the key collection and then iterate over the cloned collection. Then remove elements.
-Mike