How do I convert a Dictionary to a Lookup?

dotnetN00b picture dotnetN00b · May 2, 2012 · Viewed 7.8k times · Source

I have a Dictionary that has a signature: Dictionary<int, List<string>>. I'd like to convert it to a Lookup with a signature: Lookup<int, string>.

I tried:

Lookup<int, string> loginGroups = mapADToRole.ToLookup(ad => ad.Value, ad => ad.Key);

But that is not working so well.

Answer

Jon Skeet picture Jon Skeet · May 2, 2012

You could use:

var lookup = dictionary.SelectMany(p => p.Value
                                         .Select(x => new { p.Key, Value = x}))
                       .ToLookup(pair => pair.Key, pair => pair.Value);

(You could use KeyValuePair instead of an anonymous type - I mostly didn't for formatting reasons.)

It's pretty ugly, but it would work. Can you replace whatever code created the dictionary to start with though? That would probably be cleaner.