简体   繁体   English

在循环中从Hashtable中删除项目

[英]Removing items from Hashtable in a loop

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. Generic列表提供了一个“RemoveAll”方法,我可以传递一个匿名函数,但似乎没有HashTable的等效方法。 note: I am using .NET framework 2.0 注意:我使用的是.NET framework 2.0

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. 如果您使用的是.NET Framework 3.5或更高版本,LINQ可能会使您的目标更容易实现。

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. 如果您的应用程序是多线程的并且 .NET 4.0之前,通常最好使用ReaderWriterLock/ReaderWriterLockSlim并获取读取器锁,构建要删除的键列表,然后升级到写锁,并执行循环在列表上删除密钥。 This way, while you are iterating over the Hashtable for keys to remove, other readers can access it without being locked out. 这样,当您在Hashtable上迭代要删除的键时,其他读者可以访问它而不会被锁定。

Now if you can get to .NET 4.0, The ConcurrentDictionary is brilliant and has much less contention! 现在,如果你可以使用.NET 4.0,那么ConcurrentDictionary非常出色并且争用更少! If you stay in .NET 2.0, I'd recommend Dictionary even though it's not part of your question per se. 如果你留在.NET 2.0中,我会推荐使用Dictionary ,尽管它本身不是你问题的一部分。

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. 更新如果您的应用程序不是多线程的,则不需要锁定,但您仍需要构建密钥列表,因为在迭代时调用Remove()会使枚举器无效。 So basically, you're doing it correctly given your comment to the question. 所以基本上,在你对这个问题发表评论时,你正确地做到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM