Is there a better way to remove multiple items from a hash table based on a condition, other than saving the keys first in a list and then iterating through that and removing each item one by one? the Generic list provides a “RemoveAll” method to which I can pass an anonymous function, but it seems there isn’t an equivalent approach for HashTable. note: I am using .NET framework 2.0
Share
This really depends on your application. If your application is multi-threaded and pre .NET 4.0, it’s usually better to use a
ReaderWriterLock/ReaderWriterLockSlimand get a reader lock, build a list of the keys you want to remove, then upgrade to a write lock, and perform a loop on the list to remove the keys. This way, while you are iterating over theHashtablefor keys to remove, other readers can access it without being locked out.Now if you can get to .NET 4.0, The
ConcurrentDictionaryis brilliant and has much less contention! If you stay in .NET 2.0, I’d recommendDictionaryeven though it’s not part of your question per se.UPDATE If your application is not multi-threaded, no need to lock, but you still need to build the list of keys, because calling Remove() while iterating invalidates the enumerator. So basically, you’re doing it correctly given your comment to the question.