开发者

Removing items from Hashtable in a loop

Is there a better way to remove multiple items from a ha开发者_如何转开发sh 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


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/ReaderWriterLockSlim and 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 the Hashtable for keys to remove, other readers can access it without being locked out.

Now if you can get to .NET 4.0, The ConcurrentDictionary is brilliant and has much less contention! If you stay in .NET 2.0, I'd recommend Dictionary even 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.


Not as far as I know. What's wrong with just iterating through your list and removing the keys that way anyway? If you have to do it often, just make it a function...

If you were using .NET framework 3.5 or higher, LINQ would probably make your goal much easier to accomplish.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜