Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Collection was modified; enumeration operation may not execute.

Status
Not open for further replies.

Rationalist

Programmer
May 31, 2005
21
CA
Code:
Public Function RemoveDuplicationIntegers(ByRef TheArray As ArrayList) As ArrayList

Dim TMP1 As ArrayList
TMP1 = TheArray
Dim tmpValue1, tmpValue2 As Integer
Dim tmpfirstvalue As String = TMP1.Item(0)

Dim TMP2 As New ArrayList


TMP2.Add(tmpfirstvalue)

Dim Found As Boolean = False
For Each tmpValue1 In TMP1
Found = False
For Each tmpValue2 In TMP2
If tmpValue2 = tmpValue1 Then
Found = True
Exit For
End If
If Found = False Then
TMP2.Add(tmpValue1)
End If
Next
Next
Return (TMP2)



End Function

Error:

Collection was modified; enumeration operation may not execute.

Does anyone know what is wrong with my code?
 
You are changing the contents of the TMP2 collection by adding another item to it whilst in the middle of iterating through it.
Code:
[i][b]This line iterates the TMP2 collection[/b][/i]
For Each tmpValue2 In TMP2
        If tmpValue2 = tmpValue1 Then
            Found = True
            Exit For
        End If
        If Found = False Then
            [i][b]This line changes the TMP2 collection in the middle of iterating it[/b][/i]
            TMP2.Add(tmpValue1)
        End If
    Next
Next

Rhys
"There are some oddities in the perspective with which we see the world. The fact that we live at the bottom of a deep gravity well, on the surface of a gas-covered planet going around a nuclear fireball 90 million miles away and think this to be normal is obviously some indication of how skewed our perspective tends to be"
DOUGLAS AD
 
From the CollectionBase.GetEnumerator documentation:
MSDN said:
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current will return the element that it is set to, even if the enumerator is already invalidated.
Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top