Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Question:
Given a list of strings, return a list of lists of strings that groups all anagrams.

Ex. given
C#
{"trees", "bike", "cars", "steer", "arcs"}

return
C#
{ {"cars", "arcs"}, {"bike"}, {"trees", "steer"} }

Not sure what is the best way?
Posted
Comments
Tomas Takac 15-Dec-14 10:24am    
What did you try so far? Do you have the function to generate the anagrams?
[no name] 15-Dec-14 10:28am    
I tried it but it was too complicated. Say I used a for loop then compare each item. I just want to find a quick way such as GroupBy in LINQ.
Tomas Takac 15-Dec-14 10:39am    
Sorry, nevermind me, I cannot read apparently.

Lets try as below
C#
string[] words = new string[]{"trees", "bike", "cars", "steer", "arcs"};
var anagrams = words.GroupBy(w=>new string(w.OrderBy(c=>c).ToArray())).ToList();
 
Share this answer
 
Comments
[no name] 15-Dec-14 10:39am    
Fantastic. That is I want. +5!
BillWoodruff 15-Dec-14 21:43pm    
+5
DamithSL 15-Dec-14 21:46pm    
Thank you, BillWoodruff
Easy way?
Sort them.
If you create a class which contains the original string and it sorted into alphabetical order, you can then sort the collection of your class by the ordered strings. The ones next to each other which are identical are anagrams.

But this is your homework, so I'll let you code it!
 
Share this answer
 
Comments
Maciej Los 15-Dec-14 10:34am    
Genius!
;)
Matt T Heffron 15-Dec-14 12:37pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900