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' ]
]
*/