Search code examples
vb.netarraylistlastindexof

Remove Entries from Array starting from specific character


I have an array list that I need to modify to get rid of all the entries starting from the word that contains the period and earlier.

For example :

arrayList(0)= My
arrayList(1)= Name
arrayList(2) = Is
arrayList(3) = David.
arrayList(4) = How
arrayList(5) = Are

I need to remove arrayList(0-3)

I tried using:

dim pIndex = arrayList.LastIndexOf(arraylist.contains("."))
arrayList.RemoveRange(0,pIndex)

but just returns pIndex=-1 (meaning it can't be found)

How can I get the index of the entry with a period?


Solution

  • LastIndexOf returns the index of a specific element. contains return True or False if the list contains or not the element yo pass as parameter. Following your example, arrayList.contains(".") returns False because none of the elements of the list is "."; then arrayList.LastIndexOf(false) returns -1 because none of the elements of the list is False.

    You need to iterate throught the list:

    arrayList(0) = "My"
    arrayList(1) = "Name"
    arrayList(2) = "Is"
    arrayList(3) = "David."
    arrayList(4) = "How"
    arrayList(5) = "Are"
    
    Dim pIndex As Integer
    For pIndex = arrayList.Capacity - 1 To 0 Step -1
        If arrayList(pIndex).ToString.Contains(".") Then Exit For
    Next
    
    If pIndex <> -1 Then arrayList.RemoveRange(0, pIndex + 1)
    

    (Not tested, but it should do the work)