Dim aa, bb As New Collection

    For Each user As User In allUser
        Dim character As String = user.FirstName(0)
        If character = "b" Or character = "B" Then
        End If
        If character = "a" Or character = "A" Then
        End If

this loop use for find first letter (a-b) and add it to collection (aa,bb) but when i run , i get error "System.IndexOutOfRangeException: Collection index must be in the range 1 to the size of the collection.". Can someone give me a solution ?

Recommended Answers

All 3 Replies

Just from a glance it looks like you're not referencing your collection right, try changing b.Add(user) to bb.Add(user) and a.Add(user) to aa.Add(user)

You might want to think about making option explicit it'll catch errors like this.

This might be a little shorter and clearer

        Dim aa As New Collection
        Dim bb As New Collection

        For Each user As String In {"Abe", "Bob", "Jim"}
            Select Case UCase(user.Substring(0, 1))
                Case "A" : aa.Add(user)
                Case "B" : bb.Add(user)
            End Select

But a more general approach using a dictionary looks like

        Dim names As New Dictionary(Of String, Collection)

        For Each user As String In {"Abe", "Bob", "Jim"}

            Dim firstLetter As String = UCase(user.Substring(0, 1))

            If Not names.ContainsKey(firstLetter) Then
                names.Add(firstLetter, New Collection)
            End If



        For Each letter As String In names.Keys
            Debug.WriteLine("Names starting with the letter " & letter)
            For Each name As String In names(letter)
                Debug.WriteLine(vbTab & name.ToString)

thank both of you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.