Remove from HashTable during iteration.

Posted on 2007-11-14
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?
Question by:Henrici
  • 2
LVL 37

Accepted Solution

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

List<string> ToRemove = new List<string>();
foreach(string key in yourhashtable.Keys) {
    if(CriteriaToRemove) {
foreach(string key in ToRemove) {

Expert Comment

Comment Utility
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.

LVL 37

Expert Comment

Comment Utility
Chumad thats alot of work for a big hashtable ... (rehashing every key)

Expert Comment

Comment Utility
Forced accept.

EE Admin

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
LINQ question 7 20
Paging GridView 7 32
Help with deleting records by comparing two files using VB.NET 8 30
XML & .net 5 0
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from ( Go to that link and select download selenium in the right hand columnThat will then direct you to their downlo…
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…
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.

728 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

12 Experts available now in Live!

Get 1:1 Help Now