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
            b.Add(user)
        End If
        If character = "a" Or character = "A" Then
            a.Add(user)
        End If
    Next

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 ?

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
        Next

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

            names(firstLetter).Add(user)

        Next

        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)
            Next
        Next

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, networking, learning, and sharing knowledge.