Solved

Remove from HashTable during iteration.

Posted on 2007-11-14
5
1,157 Views
Last Modified: 2013-12-17
I have a HashTable and I wish to remove selected elements from it while I am iterating over it with IDictionaryEnumerato. Of course, the iterator is locked during iteration so I cannot do this directly. What is the fastest and most efficient alternative?
0
Comment
Question by:Henrici
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
5 Comments
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 125 total points
ID: 20282896
Keep a list of the ones you want to remove then iterate the list removing (i.e. do it in 2 steps) ....


ex:
List<string> ToRemove = new List<string>();
foreach(string key in yourhashtable.Keys) {
    if(CriteriaToRemove) {
       ToRemove.Add(key);
    }
}
foreach(string key in ToRemove) {
   yourhashtable.Remove(key);
}
0
 
LVL 8

Expert Comment

by:Chumad
ID: 20282904
Before you start looping, create a new Hashtable. During your loop, rebuild this hash table, exluding the items you want removed from it.  After the loop is done, assign your 'real' hashtable to the one you rebuilt.

0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 20283130
Chumad thats alot of work for a big hashtable ... (rehashing every key)
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20520450
Forced accept.

Computer101
EE Admin
0

Featured Post

More Than Just A Video Library

Train for your certification. Learn the latest DevOps tools. Grow your skillset to do better work.

At Linux Academy, we release new training modules every week so you'll always be up to date on the latest tech.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question