vb.netstringcollection

How to retrieve last item in StringCollection array


I'm trying to get the last item in string collection array with this:

scWords(0).Item(0) & "-" & scWords(0).Item(scWords(0).Count))

It keeps saying out of range


Solution

  • An array/collection in .NET has zero-based indexing. This means that the first entry is referred to as 0 rather than 1.

    Consider this list:

    0 Apple
    1 Orange
    2 Kiwi
    3 Watermelon
    

    The list clearly has 4 items in it, but since it's 0-based indexing, the last item (Watermelon) is 3, not 4. This is why when you use .Count (which returns how many items the list has), it says out of range.

    As you can see from the example, using .Count -1 will return the last item.