如何将字典转换为查找? [重复]

时间:2022-10-30 15:50:06

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>.

我有一个具有签名的Dictionary:Dictionary >。我想将它转换为带签名的Lookup:Lookup ,string> ,list>

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.

这很难看,但它会起作用。你可以替换创建字典的任何代码吗?那可能会更清洁。