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

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

    How about this (no iteration needed):

    NeededList = (NeededList.Where(Function(Needed) IsNeeded(Needed)).ToList
    
    Function IsNeeded(Needed As ...) As Boolean
        ...
        Return Not dr.HasRows
    End Function
    
    0 讨论(0)
  • 2021-01-17 10:03

    You can also invert the order of the list's elements and still use For Each using the IEnumerable Cast and Reverse extensions.

    Simple example using a List(Of String):

    For Each Needed In NeededList.Cast(Of List(Of String)).Reverse()
        If dr.HasRows Then
            NeededList.Remove(Needed)
        End If
    Next
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • Go for safe and make a copy with ToList():

    For Each Needed In NeededList.ToList()
        Dim Ticker = Needed.Split("-")(0).Trim()
        ...
        If dr.HasRows Then
            NeededList.Remove(Needed)
        End If
    Next
    
    0 讨论(0)
  • 2021-01-17 10:13

    The contents of an array (or anything else you can fast enumerate with For Each can not be modified with a For Each loop. You need to use a simple For loop and iterate through every index.

    Hint: Because you'll be deleting indexes, I suggest starting at the last index and work your way toward the first index so you don't skip over one every time you delete one.

    0 讨论(0)
  • 2021-01-17 10:16

    No you can not remove from a List that you are working on e.g. For Each Str As String In listOfStrings If Str.Equals("Pat") Then Dim index = listOfStrings.IndexOf(Str) listOfStrings .RemoveAt(index) End If Next

    But this way will work make a copy of your list and delete from it e.g. For Each Str As String In listOfStrings If Str.Equals("Pat") Then Dim index = listOfStringsCopy.IndexOf(Str) listOfStringsCopy.RemoveAt(index) End If Next

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