Removing Items in a List While Iterating Through It with For Each Loop

前端 未结 7 2096
小鲜肉
小鲜肉 2021-01-17 09:56

I have a list named NeededList I need to check each item in this list to see if it exists in my database. If it does exist in the database I need to remove it

相关标签:
7条回答
  • 2021-01-17 10:21

    No you can't do that using a for each, but you can do that using the old fashioned for .. loop.
    The trick is to start from the end and looping backwards.

    For x = NeededList.Count - 1 to 0 Step -1
        ' Get the element to evaluate....
        Dim Needed = NeededList(x)
        .....
        If dr.HasRows Then
            NeededList.RemoveAt(x)
        End If
    Next
    

    You need to approach the loop in this way because you don't risk to skip elements because the current one has been deleted.

    For example, suppose that you remove the fourth element in the collection, after that, the fifth element becomes the fourth. But then the indexer goes up to 5. In this way, the previous fifth element (now in fourth position) is never evaluated. Of course you could try to change the value of the indexer but this ends always in bad code and bugs waiting to happen.

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