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
Solved

Remove from HashTable during iteration.

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

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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 new code templates in NetBeans IDE 8.0 for Windows.

809 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