Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Dictionary to a Lookup? [duplicate]

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.

like image 445
dotnetN00b Avatar asked May 02 '12 19:05

dotnetN00b


People also ask

Can Python dictionary have duplicate values?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Does dictionary allow duplicate values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can Vlookup have duplicate keys C#?

The answer is: yes.


1 Answers

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.

like image 145
Jon Skeet Avatar answered Oct 19 '22 09:10

Jon Skeet