I am trying to remove my current item in for each loop if some criterai matches but its triggering error after removing and looping again.
My sample code:
For Each Item As BookingRoom In myBookedRooms
If Item.RoomInfo.UIN = myRoom.UIN Then
myBookedRooms.Remove(Item)
Continue For
End If
Next
*Note RoomInfo and myRoom are both instances of Room Class
I am using myBookedRooms.remove
but its trigerring error so what can be the correct way for doing it? ie, remove booked room if the room id matches with selected one
The problem is you're modifying the collection while iterating over it.
You can iterate the list in reverse with a for loop:
For i = myBookedRooms.Count - 1 To 0 Step -1
If myBookedRooms(i).RoomInfo.UIN = myRoom.UIN Then
myBookedRooms.RemoveAt(i)
End If
Next
Alternately, you can use the RemoveAll
method:
myBookedRooms.RemoveAll(Function(item) item.RoomInfo.UIN = myRoom.UIN)
Another option is to use the Enumerable.Where
method to filter the results, but unlike the previous two approaches you would need to reverse your logic check to exclude the matching items since the intention is to remove them:
myBookedRooms = myBookedRooms
.Where(Function(item) item.RoomInfo.UIN <> myRoom.UIN)
.ToList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With