Murky Macadamian
Murky Macadamian

Reputation: 58

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

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.

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?

Upvotes: 2

Views: 8516

Answers (1)

Tommy
Tommy

Reputation: 39807

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

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

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:

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

Upvotes: 5

Related Questions