my Dictionary removal code correct?

This is a discussion on my Dictionary removal code correct? within the C# Programming forums, part of the General Programming Boards category; Hello everyone, I want to iterator a Dictionary variable instance, and remove all elements under a specific condition. Here is ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    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?

    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);
                }
            }

    thanks in advance,
    George

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    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.
    Code:
    foreach(Entry in Dictionary)
    {
      if(Entry should be removed)
      {
        TempList.Add(Entry);
      }
    }
    
    foreach(Entry in TempList)
    {
      Dictionary.Remove(Entry);
    }
    MagosX.com

    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, 04: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, 12:33 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21