Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,560 questions

51,419 answers

573 users

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 12 hours ago by avibootz
edited 12 hours ago by avibootz
...