问题
I am trying to remove all items from a combo box list that begin with "~$".
For Each item As String In cstmcmbxDocs.Items
If Not cstmcmbxDocs.Items.Contains("~$") Then
Dim STR As Int16 = cstmcmbxDocs.FindString("~$")
'gets the index of the item which contains "~$"
cstmcmbxDocs.Items.RemoveAt([STR])
End If
Next
But it only returns one instance which it removes. It doesn't continue searching - what am i missing here? (Note that I am using 3.5 and not 4+ because it needs to be compatible with XP)
回答1:
You cannot modify a collection (add or delete) as you iterate using For Each/Next. Nor can you use a standard For n As Int32 loop. Instead:
For n As Int32 = cstmcmbxDocs.Items.Count -1 To 0 Step -1
...
If [your criteria here] Then
cstmcmbxDocs.Items.RemoveAt(n) ' remove current one
End If
Next n
You should also turn on Option Strict: Dim STR As Int16 = cstmcmbxDocs.FindString("~$") wont compile. And you do not need to use FindString - your loop is already going to look at each item, so just examine each for the condition.
Why a For Each loop fails
For Each item As String In cstmcmbxDocs.Items
Removing from inside this type of loop should result in an InvalidOperationException. If you click the Get general help link you find this:
IEnumerator.MoveNext
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.
Why a forward For n loop will fail
Consider:
Dim lst As New List(Of String)
lst.AddRange(New String() {"Alpha", "Beta", "Gamma", "Delta", "Echo"})
For n As Int32 = 0 To lst.Count - 1
If lst(n) = "Gamma" OrElse lst(n) = "Delta" Then
lst.RemoveAt(n)
End If
Next
- When (n=2) "Gamma" is the current item.
- Your code
RemoveAt(n)so everything moves up one.nnow points to "Delta" - Then
Nextincrementsnso it now points to "Echo"
"Delta" is never evaluated in the loop because it is skipped. Every element after a deleted one will be skipped. This is what MSDN means by enumerator is irrecoverably invalidated.
In this case, your loop will also run out of items! The end loop value, lst.Count - 1 is calculated only at the start of the loop. Removing items reduces the actual size so it will eventually crash with an ArgumentOutOfRangeException. As before, loop backwards using For n:
For n As Int32 = lst.Count - 1 To 0 Step - 1
If lst(n) = "Gamma" OrElse lst(n) = "Delta" Then
lst.RemoveAt(n)
End If
Next
Now, when items are removed, the part of the list which is reordered is the part the code has already tested.
来源:https://stackoverflow.com/questions/20176130/remove-items-from-collection-in-a-loop-combo-box-items