开发者

Changing increment variables causes for loop to go over limit

In my loop I am trying to remove items from a list that have a certain name. I can't do this with a for-each, so I tried a regular for-loop. It seems the for loop is not working as expected. It always goes over the limit. I had to put an if-then to break out of the loop (very ugly solution). I'm trying to find the correct way to accomplish this.

Dim canShowNextTable As Boolean = False
    Dim allTablesInTab As List(Of Control) = ctrlFinder.GetTypeOfControls("Table", parentForm.Controls)
    Dim totalTables As Integer = allTablesInTab.Count - 1
    For i As Integer = 0 To totalTables
        If allTablesInTab.Item(i).ID = "CustomerTable" Or _
            allTablesInTab.Item(i).ID = "PMTable" Or _
            allTablesInTab.Item(i).ID = "TableAListClrnCheck" Or _
            allTablesInTab.Item(i).ID = "TableBListClrnCheck" Or _
            allTablesInTab.Item(i).ID = "TableCListClrnCheck" Or _
            allTablesInTab.Item(i).ID = "TableDListClrnCheck" Or _
            allTablesInTab.Item(i).ID = "TableSignature" Then       '' If the ID is one of these remove it from list
            allTablesInTab.Remove(开发者_开发问答allTablesInTab.Item(i))
            totalTables = totalTables - 1                           '' Decrement number of tables to loop through
            i = -1                                                  '' Reset counter to prevent going over or premature stopping
        End If
        If i = 3 AndAlso totalTables = 3 Then                       '' Since loop continuously goes over limit, use if-then to exit for-loop
            Exit For
        End If
    Next


You need to traverse your loop in reverse because once you remove an item the total count has changed and is no longer correct. Looping in reverse avoids this issue.

For i As Integer = totalTables To 0 Step -1

Also, instead of allTablesInTab.Remove(allTablesInTab.Item(i)) you can use:

allTablesInTab.RemoveAt(i)

Work through this logic on paper or the debugger to properly grasp the concept of what's happening. You might also find this related question useful. It's in C# but the concepts are the same: How to remove elements from a generic list while iterating around it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜