How do I convert a Dictionary to a Lookup? [duplic

2019-02-08 17:40发布

This question already has an answer here:

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.

1条回答
迷人小祖宗
2楼-- · 2019-02-08 18:01

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.

查看更多
登录 后发表回答