It happens so often to me that I need to remove items from a List(Of) if a certain condition is met.
I prefer to do it this way:
For Each nClass As SomeClass In MyList
If (Something) Then
MyList.Remove(nClass)
End If
Next
However, when I remove an item, the collection is changed, and the For Next Statement can't proceed, and a System.InvalidOperationException is thrown.
I wonder if there's any general way to do this properly without writing big workarounds.
Can anybody tell how this should be done correctly?
I'm attaching a test code to see the error:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim nList As New List(Of SomeClass)
For i As Integer = 0 To 5
Dim nNewItem As New SomeClass
nNewItem.Int = i
nNewItem.Text = "My text " + i.ToString
nList.Add(nNewItem)
Next
For Each nItem As SomeClass In nList
If nItem.Int > 1 And nItem.Int < 5 Then
nList.Remove(nItem)
End If
Next
End Sub
End Class
Public Class SomeClass
Private _iInt As Integer = 0
Private _sText As String = String.Empty
Public Property Int() As Integer
Get
Return _iInt
End Get
Set(value As Integer)
_iInt = value
End Set
End Property
Public Property Text() As String
Get
Return _sText
End Get
Set(value As String)
_sText = value
End Set
End Property
End Class