Help with removing key/value pair form dictionary class

J. Scott Elblein

Well-known member
Joined
Dec 14, 2006
Messages
166
Location
Chicago
Programming Experience
10+
Hi all, am I doing this properly? I get (sometimes an IDE crash) and sometimes an error. I have 2 dictionary objects loaded with keys/values. Many are the same, so what I am doing is looping through both of them, and if I find the same key/value pair in them, I want to remove them from both collections, and then in the end I will do something with the remaining contents of each collection. I hope I made that understandable. =)

The problem I am running into is trying to .Remove them once they have both been compared and are the same contents. Here is the current code I am using:

VB.NET:
            For Each itm In dictCompare ' dictCompare is the Old List

                For Each itm2 In col ' col is the Current list

                    If itm2.Value.Contains(itm.Value) Then

                        ' Found it, remove key/value from both collections
                        itm.Key.Remove(itm.Key.ToString)
                        itm2.Key.Remove(itm.Key.ToString)

                    End If

                Next

            Next

From all my reading, it seems like just using the string in the second overload or .Remove should of been enough, but I get an error about needing a start index, so if I just add 0, to it, I get another error. I am wondering if it won't allow me to remove it, because it is the currently selected key in the loop(s)?

Thanks for all help, as always. :)
 
VB.NET:
Dim dct1 As New Dictionary(Of String, Integer)
dct1.Add("key1", 1)
dct1.Add("key2", 2)
Dim dct2 As New Dictionary(Of String, Integer)
dct2.Add("key1", 1)
dct2.Add("key3", 3)

Dim Keys(dct1.Keys.Count - 1) As String
dct1.Keys.CopyTo(Keys, 0)

For Each key As String In Keys
    If dct2.ContainsKey(key) Then
        dct1.Remove(key)
        dct2.Remove(key)
    End If
Next
 
Back
Top