Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Current Item from List if some criteria matches

Tags:

list

vb.net

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

like image 759
KoolKabin Avatar asked Jun 02 '11 12:06

KoolKabin


1 Answers

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()
like image 62
Ahmad Mageed Avatar answered Oct 20 '22 03:10

Ahmad Mageed