How do I convert a Dictionary to a Lookup?

.net, c#, dictionary, list, lookup

Solution

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.

Problem

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.

Original source

Related problems