• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 394
  • Last Modified:

How to find the Nth instance of an item in an arraylist?

I need a function that takes the item being searched for, the arraylist being searched and the number of the instance and returns the position of the instance.
0
NevSoFly
Asked:
NevSoFly
1 Solution
 
quizwedgeCommented:
Returns the index unless it can't find it, in which case it returns -1

 Private Function ReturnNthInstance(ByVal SearchFor As String, ByVal SearchList As ArrayList, ByVal NumberOfInstances As Integer) As Integer
        Dim Counter As Integer = 0
        Dim i As Integer
        For i = 0 To SearchList.Count - 1
            If CStr(SearchList(i)) = SearchFor Then
                Counter += 1
            End If

            If Counter = NumberOfInstances Then
                Return i
            End If
        Next

        Return -1
    End Function

Open in new window

0
 
NevSoFlyAuthor Commented:
perfect.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now