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,845 questions

51,766 answers

573 users

How to convert a list of strings and group all the anagrams into sublists in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Linq
 
Module Program
    ' Groups a list of strings into sublists of anagrams.
    Function GroupAnagrams(words As List(Of String)) As List(Of List(Of String))
        If words Is Nothing Then
            Throw New ArgumentException("Input must be a list of strings.")
        End If
 
        Dim map As New Dictionary(Of String, List(Of String))()
 
        For Each word In words
            If word Is Nothing Then
                Throw New ArgumentException("All elements in the list must be non-null strings.")
            End If
 
            ' Sort characters
            Dim chars As Char() = word.ToCharArray()
            Array.Sort(chars)
            Dim sorted As String = New String(chars)
 
            ' Group words by their sorted key
            If Not map.ContainsKey(sorted) Then
                map(sorted) = New List(Of String)()
            End If
            map(sorted).Add(word)
        Next
 
        ' Return grouped anagrams as a list of lists
        Return map.Values.ToList()
    End Function
 
    Sub Main()
        Try
			Dim lst As New List(Of String) From {"eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"}
			Dim result As List(Of List(Of String)) = GroupAnagrams(lst)
 
            ' Print result
            Console.WriteLine("[")
            For Each group In result
                Console.Write("  [ ")
                For i As Integer = 0 To group.Count - 1
                    Console.Write("'" & group(i) & "'")
                    If i < group.Count - 1 Then
                        Console.Write(", ")
                    End If
                Next
                Console.WriteLine(" ]")
            Next
            Console.WriteLine("]")
        Catch ex As Exception
            Console.Error.WriteLine(ex.Message)
        End Try
    End Sub
End Module
 
 
 
' run:
'
' [
'   [ 'eat', 'tea', 'ate' ]
'   [ 'rop', 'orp', 'pro' ]
'   [ 'nat', 'tan' ]
'   [ 'bat' ]
' ]
'

 



answered Nov 15, 2025 by avibootz
edited Nov 15, 2025 by avibootz
...