What's the best way to transform an IEnumerable
into a lookup- or dictionary-like structure, but with multiple keys per value?
What I'm looking for is something that does roughly the same thing as this, and in a generic way:
var wordsByLetter = new Dictionary<char, HashSet<string>>();
foreach (string word in words)
{
foreach (char letter in word.Distinct())
{
if (!wordsByLetter.ContainsKey(letter))
{
wordsByLetter.Add(letter, new HashSet<string>());
}
wordsByLetter[letter].Add(word);
}
}
So the result is a dictionary mapping each letter used to the set of words that contain that letter.
For example, if words
contained {"foo", "faz", "zoo"}
then the resulting dictionary would contain:
'a' -> {"faz"}
'f' -> {"foo", "faz"}
'o' -> {"foo", "zoo"}
'z' -> {"faz", "zoo"}
I could turn my code example into an extension method, but is there a built-in function or better algorithm to use?