Remove Items from Collection in a loop (Combo Box items)

后端 未结 1 2010
半阙折子戏
半阙折子戏 2020-12-22 03:16

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.Con         


        
相关标签:
1条回答
  • 2020-12-22 03:46

    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. n now points to "Delta"
    • Then Next increments n so 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.

    0 讨论(0)
提交回复
热议问题