Solved

Remove from HashTable during iteration.

Posted on 2007-11-14
5
1,148 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
  • 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

813 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now