My goal is to reduce the number of key / value pairs in a dictionary object by comparing the keys in the dictionary object to words contained in an array and removing the key / value pairs where the key (a string) is equal to one of the strings in my array.
In the code below, AssignedNumbers represents the Dictionary object. The keys are strings, the values are integers ... it could look like this:
("pair" , 0)
("of" , 1)
("shoes" , 2)
The one-dimensional array named RejectedWordsArray, might contain the strings "a" and "of".
Using the above scenario, I want to compare each word in the RejectedWordsArray against the keys in the AssignedNumbers dictionary and remove those dictionary key / value pairs where the RejectedWordsArray value equals a dictionary key. If the array values and dictionary keys were as stated above, the word "of" would be found as common to the array and dictionary and I would want the key / value pair ("of", 1) removed from the dictionary
Following is the code that does not work:
<%@ Page Language="VB" Debug="True"%>
<%
@ Import Namespace="System.Collections.Generic" %>' To get the keys alone, use the Keys property.
Dim keyColl As Dictionary(Of String, Integer).KeyCollection = AssignedNumbers.Keys '' ContainsKey can be used to test keys before inserting / removing them.
For f = 0 To UBound(RejectedWordsArray) For Each g As String In keyColl
If AssignedNumbers.ContainsKey(RejectedWordsArray(f)) Then
AssignedNumbers.Remove(g)
End IfNext g
Next
*** End of Code *******************************************************************************************************
Running the above code generates the following error message:
Collection was modified; enumeration operation may not execute.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
Source Error:
Line 280: AssignedNumbers.Remove(g)
Line 281: End If
Line 282: Next g
Line 283: Next
Line 284: |
Please help me build the code that will successfully remove the qualified dictionary key / value pairs?