4
Answers

my Dictionary removal code correct?

George George

George George

16y
2.8k
1

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<string, Foo>.KeyCollection keys = dic.Keys;
        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

Answers (4)