[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Remove from HashTable during iteration.

Posted on 2007-11-14
5
Medium Priority
?
1,163 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
4 Comments
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 500 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
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.

830 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