遍历 Hashtable 并有条件地删除 VB.NET 中条目的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29243684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:54:53  来源:igfitidea点击:

Best way to iterate through Hashtable and conditionally remove entries in VB.NET

vb.netiterationhashtable

提问by Murky Macadamian

In VB.NET, I have a HashTable that I would like to iterate through and conditionally remove entries from. I've written the following code that does the job perfectly, but I'd like to know if there are any creative ways to simplify the code. It just doesn't seem right to have to create a second list to perform this operation.

在 VB.NET 中,我有一个 HashTable,我想遍历它并有条件地从中删除条目。我已经编写了以下代码,可以完美地完成这项工作,但我想知道是否有任何创造性的方法来简化代码。必须创建第二个列表来执行此操作似乎不太正确。

Here's what I've written:

这是我写的:

Dim ModsToRemove As New List(Of String)
For Each ModKey As DictionaryEntry In ModHashTable
    If ModKey.Key.ToString.Contains("Criteria") Then
        ModsToRemove.Add(ModKey.Key.ToString)
    End If
Next
For Each ModKey As String In ModsToRemove
    ModHashTable.Remove(ModKey)
Next

Is there another way to perform the same operation that doesn't require the creation of a second list and a second loop? Is it possible to remove entries from something you are iterating through without throwing an error in VB.NET? Is doing so universally a bad idea?

是否有另一种方法可以执行不需要创建第二个列表和第二个循环的相同操作?是否可以从您正在迭代的内容中删除条目而不会在 VB.NET 中引发错误?普遍这样做是个坏主意吗?

回答by Tommy

With a little bit of help from Resharper and LINQ, you can simplify your expression in the following ways.

在 Resharper 和 LINQ 的帮助下,您可以通过以下方式简化您的表达式。

This code block here can be rewritten to use LINQ instead of the embedded IFstatement

这里的代码块可以重写为使用 LINQ 而不是嵌入IF语句

For Each ModKey As DictionaryEntry In ModHashTable
    If ModKey.Key.ToString.Contains("Criteria") Then
        ModsToRemove.Add(ModKey.Key.ToString)
    End If
Next

Is equivalent to

相当于

Dim modsToRemove As List(Of String) = (From modKey As DictionaryEntry In 
modHashTable Where modKey.Key.ToString.Contains("Criteria") 
Select modKey.Key.ToString).ToList()

Combining this with your actual loop to remove the items from the Hashtable, you should be able to get the equivalent functionality of your example above with the following 3 lines of code:

将此与您的实际循环相结合以从 Hashtable 中删除项目,您应该能够使用以下 3 行代码获得与上述示例等效的功能:

For Each key As String In (From modkey As DictionaryEntry In modHashTable Where modkey.Key.ToString.Contains("Criteria") Select modkey.Key.ToString).ToList()
  modHashTable.Remove(key)
Next