Thread: my Dictionary removal code correct?

  1. #1
    Registered User
    Join Date
    May 2006

    my Dictionary removal code correct?

    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?

            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?

    thanks in advance,

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    In general you should never remove an item from a collection while you're traversing it. You might want to create a temporary list to store all items to remove in, then traversing that list later. Is kind of a hack, but works.
    foreach(Entry in Dictionary)
      if(Entry should be removed)
    foreach(Entry in TempList)

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  2. Obfuscated Code Contest: The Results
    By Stack Overflow in forum Contests Board
    Replies: 29
    Last Post: 02-18-2005, 05:39 PM
  3. Problem : Threads WILL NOT DIE!!
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2004, 01:37 PM
  4. Seems like correct code, but results are not right...
    By OmniMirror in forum C Programming
    Replies: 4
    Last Post: 02-13-2003, 01:33 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM