?
Solved

Remove from HashTable during iteration.

Posted on 2007-11-14
5
Medium Priority
?
1,159 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 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

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

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…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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.
Suggested Courses

800 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