I am trying to remove elements from a Dictionary<string, List<string>>
in C# when the count of the list<string>
is lesser than or equal to 1.
I got some code working but it is not elegant and I have a gut feeling that this can be done elegantly in linq.
This is the code I have now
Dictionary<string,List<string>> FindAnagrams(List<string> dictionary)
{
Dictionary<string, List<string>> anagrams = new Dictionary<string, List<string>>();
foreach (string word in dictionary)
{
char[] charArray=word.ToCharArray();
Array.Sort(charArray);
string sorted=new string(charArray);
if (anagrams.ContainsKey(sorted))
anagrams[sorted].Add(word);
else
anagrams.Add(sorted, new List<string>() { word });
}
List<string> nonAnagrams = new List<string>();
foreach (var sorted in anagrams.Keys)
if (anagrams[sorted].Count == 1)
nonAnagrams.Add(sorted);
foreach(string word in nonAnagrams)
anagrams.Remove(word);
return anagrams;
}
Below is how far I got using linq but this ain't working.
var realAna = from keys in anagrams.Keys
where anagrams[keys].Count >1
select anagrams.values;
To put the problem in context I am trying to find anagrams from a dictionary, I consider a words as having anagrams if the sorted key has more than one value associated with it.