如果某些条件匹配,则从列表中删除当前项

Koo*_*bin 5 vb.net list

我试图删除我的每个循环中的当前项目,如果一些criterai匹配但其删除和循环再次循环后的触发错误.

我的示例代码:

        For Each Item As BookingRoom In myBookedRooms
            If Item.RoomInfo.UIN = myRoom.UIN Then
                myBookedRooms.Remove(Item)
                Continue For
            End If
        Next
Run Code Online (Sandbox Code Playgroud)

*注意RoomInfo和myRoom都是Room Class的实例

我正在使用myBookedRooms.remove但它的trigerring错误,所以这可能是正确的方法吗?即,如果房间ID与所选房间ID匹配,则删除预订的房间

Ahm*_*eed 9

问题是你在迭代时修改集合.

您可以使用for循环反向迭代列表:

For i = myBookedRooms.Count - 1 To 0 Step -1
    If myBookedRooms(i).RoomInfo.UIN = myRoom.UIN Then
        myBookedRooms.RemoveAt(i)
    End If
Next
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用以下RemoveAll方法:

myBookedRooms.RemoveAll(Function(item) item.RoomInfo.UIN = myRoom.UIN)
Run Code Online (Sandbox Code Playgroud)

另一个选择是使用该Enumerable.Where方法来过滤结果,但与前两种方法不同,您需要反转逻辑检查以排除匹配项,因为目的是删除它们:

myBookedRooms = myBookedRooms
                    .Where(Function(item) item.RoomInfo.UIN <> myRoom.UIN)
                    .ToList()
Run Code Online (Sandbox Code Playgroud)