Reputation: 793
What I did here is save table of two columns in a arraylist and dictionary.
Dim result As New ArrayList()
While dr.Read()
' Insert each column into a dictionary
Dim dict As New Dictionary(Of String, Object)
For count As Integer = 0 To (dr.FieldCount - 1)
dict.Add(dr.GetName(count), dr(count))
Next
' Add the dictionary to the ArrayList
result.Add(dict)
End While
......... Now I want to go through it and when it found - remove it. Its for time saving as there are lots of data. I get error "Collection was modified; enumeration operation may not execute." after removal and going to next. I understand the problem but how do I overcome this? How to convert it to loop with removal?
For Each dat As Dictionary(Of String, Object) In result
comp2 = dat("ID")
If comp2 = comp Then
advcode = advcode & "," & dat("ADVC")
found = True
firstattempt = False
result.Remove(dat)
Else
If found And Not firstattempt Then Exit For
End If
Next
Upvotes: 1
Views: 3490
Reputation: 9888
Try this:
Dim iCont As Integer = 0
While result.Count > iCont
Dim dat As Dictionary(Of String, Object) = CType(result(iCont), Dictionary(Of String, Object))
comp2 = dat("ID")
If comp2 = comp Then
advcode = advcode & "," & dat("ADVC")
found = True
firstattempt = False
result.Remove(dat)
Else
If found And Not firstattempt Then Exit For
iCont += 1
End If
End While
Upvotes: 1
Reputation: 2140
normally two ways to fix it:
traverse the arraylist from the back:
For i As Integer = result.Count - 1 To 0 Step -1
Dim dat = CType(result(i), Dictionary(Of String, Object))
' ...
' if found:
result.RemoveAt(i)
Next
copy the arraylist to a new array:
For Each Dat As Dictionary(Of String, Object) In result.ToArray()
' do your stuff here
Next
option 1 should give better performance
Upvotes: 1
Reputation: 101142
Why don't you use a List(Of Dictionary(Of String, Object))
instead of an ArrayList
? That would make the code clearer.
Nonetheless, just copy the collection into a new one, so removing an element from the original collection does not stop the iteration of the copy:
For Each dat As Dictionary(Of String, Object) In result.ToArray() ' Copy into new array '
comp2 = dat("ID")
If comp2 = comp Then
advcode = advcode & "," & dat("ADVC")
found = True
firstattempt = False
result.Remove(dat)
Else
If found And Not firstattempt Then Exit For
End If
Next
Upvotes: 2