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 C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Groups a list of strings into sublists of anagrams.
    public static List<List<string>> GroupAnagrams(List<string> words) {
        if (words == null)
            throw new ArgumentException("Input must be a list of strings.");
 
        var map = new Dictionary<string, List<string>>();
 
        foreach (var word in words) {
            if (word == null)
                throw new ArgumentException("All elements in the list must be non-null strings.");
 
            // Sort characters
            var chars = word.ToCharArray();
            Array.Sort(chars);
            var sorted = new string(chars);
 
            // Group words by their sorted key
            if (!map.ContainsKey(sorted)) {
                map[sorted] = new List<string>();
            }
            map[sorted].Add(word);
        }
 
        // Return grouped anagrams as a list of lists
        return map.Values.ToList();
    }
 
    static void Main()
    {
        try
        {
            var lst = new List<string> { "eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro" };
            var result = GroupAnagrams(lst);
 
            // Print result
            Console.WriteLine("[");
            foreach (var group in result) {
                Console.Write("  [ ");
                for (int i = 0; i < group.Count; i++) {
                    Console.Write($"'{group[i]}'");
                    if (i + 1 < group.Count)
                        Console.Write(", ");
                }
                Console.WriteLine(" ]");
            }
            Console.WriteLine("]");
        }
        catch (Exception ex) {
            Console.Error.WriteLine(ex.Message);
        }
    }
}
 
 
 
/*
run:
 
[
  [ 'eat', 'tea', 'ate' ]
  [ 'rop', 'orp', 'pro' ]
  [ 'nat', 'tan' ]
  [ 'bat' ]
]
 
*/

 



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