How to group words by first letter in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Program

    Sub Main()

        ' List of words to group
        Dim words As New List(Of String) From {
            "Python", "JavaScript", "C", "Java", "C#", "PHP",
            "C++", "Pascal", "SQL", "Rust"
        }

        Dim groupedWords As Dictionary(Of Char, List(Of String)) =
            GroupByFirstLetter(words)

        ' Print each group 
        For Each kvp In groupedWords
            Console.WriteLine($"{kvp.Key}: [{String.Join(", ", kvp.Value)}]")
        Next

    End Sub


    ''' <summary>
    ''' Groups a list of words by their first letter.
    ''' </summary>
    ''' <param name="words">List of words to group</param>
    ''' <returns>Dictionary where each key is a letter and each value is a list of words</returns>
    Function GroupByFirstLetter(words As List(Of String)) As Dictionary(Of Char, List(Of String))

        ' Dictionary that maps a character to a list of words
        Dim groups As New Dictionary(Of Char, List(Of String))()

        ' Loop through each word
        For Each word In words
            ' Extract the first letter
            Dim firstLetter As Char = word(0)

            ' If the key doesn't exist, create a new empty list
            If Not groups.ContainsKey(firstLetter) Then
                groups(firstLetter) = New List(Of String)()
            End If

            ' Add the word to the appropriate list
            groups(firstLetter).Add(word)
        Next

        Return groups
    End Function

End Module



' run:
'
' P: [Python, PHP, Pascal]
' J: [JavaScript, Java]
' C: [C, C#, C++]
' S: [SQL]
' R: [Rust]
' 

 



answered Jan 16 by avibootz
edited Jan 16 by avibootz
...