Removing items from a list (from t) in vb.net crash

I have a generic list from which I remove items from List.Remove(Object). I deleted the items, but whenever I get to the fifth item, I delete it and does not remove it from the list. It does not seem to matter what I delete, but every time I try to delete five elements that it fails on the fifth element.

What could be the reason for this? Looking at the documentation for List(Of T).Remove, he does not indicate which algorithm they use to remove the item.

+5
source share
5 answers

Removewill match based on the call .Equalson your objects. By default, for this object, it will correspond to only one object. If you want two objects with the same properties to be considered equal, even if they are not the same object, you need to redefine the method Equalsand put your logic there.

However, another good option is to use RemoveAlland pass an anonymous delegate or lambda expression with the criteria you are looking for. For example:.

customers.RemoveAll(customer => customer.LastName.Equals(myCustomer.LastName));

Of course, this only works if you really want to remove all the relevant elements and / or if you are sure that there will only be one that matches.

+12
source

, -1, .

+2

? , ? , 0. - For , , .

0

, , , . a , , .

:

  • ,
  • , .

Loop Backwards:

, Collection(Of T) ( List(Of T), list RemoveAll, ).
-. , .

<Extension()>
Public Sub RemoveEach(Of T)(ByRef col As Collection(Of T),
                            ByVal match As Func(Of T, Boolean))
    For i = col.Count - 1 To 0 Step -1
        If match(col(i)) Then col.RemoveAt(i)
    Next
End Sub

:

Dim col = New Collection(Of Integer)({1, 2, 3, 4}.ToList)
col.RemoveEach(Function(i) (i Mod 2) = 0)
'Produces list of 1 & 3

:

, RemoveAt Remove, , . , For Loop, ToList , . , , . , , , .

<Extension()>
Public Sub RemoveEachObject(Of T)(ByRef col As Collection(Of T), 
                                  ByVal match As Func(Of T, Boolean))
    For Each o As T In col.ToList()
        If match(o) Then col.Remove(o)
    Next
End Sub

foreach.

0

If you use a loop to delete items, you should consider using foreach, it is more suitable for collections, lists, and objects with numbers

-1
source

All Articles