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

前端 未结 7 2093
小鲜肉
小鲜肉 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:07

    You can use a For loop iterating through every index with Step -1.

    For i as Integer = NeededList.Count - 1 to 0 Step -1
    
        Dim Needed = NeededList(i)
    
        'this is a copy of your code
        Dim Ticker = Needed.Split("-")(0).Trim()
        Dim Year = Needed.Split("-")(1).Trim()
        Dim Period = Needed.Split("-")(2).Trim()
        Dim Table = Needed.Split("-")(3).Trim()
    
        Dim dr As OleDbDataReader
        Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & Table & " WHERE Ticker = ? AND [Year] = ? AND Period = ?", con)
        cmd2.Parameters.AddWithValue("?", Ticker)
        cmd2.Parameters.AddWithValue("?", Year)
        cmd2.Parameters.AddWithValue("?", Period)
        dr = cmd2.ExecuteReader
    
        'MODIFIED CODE
        If dr.HasRows Then NeededList.RemoveAt(i)
    
    Next i
    

提交回复
热议问题