我如何转换词典为查找? [英] How do I convert a Dictionary to a Lookup?

查看:216
本文介绍了我如何转换词典为查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,有一个签名:词典< INT,列表和LT;字符串>> 。我想将其转换为查找一个签名:查找< INT,字符串>

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

我想:

Lookup<int, string> loginGroups = mapADToRole.ToLookup(ad => ad.Value, ad => ad.Key);

但是,这是行不通的这么好。

But that is not working so well.

推荐答案

您可以使用:

var lookup = dictionary.SelectMany(p => p.Value
                                         .Select(x => new { p.Key, Value = x}))
                       .ToLookup(pair => pair.Key, pair => pair.Value);

(您可以使用 KeyValuePair <​​/ code>,而不是匿名类型 - 我大多没有用于格式化的原因)

(You could use KeyValuePair instead of an anonymous type - I mostly didn't for formatting reasons.)

这是pretty的丑陋,但它的工作。您可以更换任何code的的字典开始与关系吗?这很可能是更清洁。

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.

这篇关于我如何转换词典为查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆