This question already has an answer here:
这个问题在这里已有答案:
- LINQ Convert Dictionary to Lookup 2 answers
- LINQ将字典转换为查找2个答案
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>
.
我有一个具有签名的Dictionary:Dictionary
I tried:
我试过了:
Lookup<int, string> loginGroups = mapADToRole.ToLookup(ad => ad.Value, ad => ad.Key);
But that is not working so well.
但这并没有那么好。
1 个解决方案
#1
17
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.)
(您可以使用KeyValuePair而不是匿名类型 - 我主要不是出于格式化原因。)
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.
这很难看,但它会起作用。你可以替换创建字典的任何代码吗?那可能会更清洁。
#1
17
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.)
(您可以使用KeyValuePair而不是匿名类型 - 我主要不是出于格式化原因。)
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.
这很难看,但它会起作用。你可以替换创建字典的任何代码吗?那可能会更清洁。