c# - 从具有常见值的字典中获取 TKey,其中 TValue 是 List
问题描述
我有一本看起来像这样的字典:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>()
{
{"a" , new List<string> { "Red","Yellow"} },
{"b" , new List<string> { "Blue","Red"} },
{"c" , new List<string> { "Green","Orange"} },
{"d" , new List<string> { "Black","Green"} },
};
我需要作为字典输出,dict
其中的公共值List<string>
应该是键,值应该是键列表。
例如:
Red: [a,b]
Green: [c,d]
我不知道如何用list
in dictionary
as解决这个问题TValue
。
请解释我如何处理字典中的列表。
解决方案
您可以用扁平化您的字典SelectMany
并获得看起来像的简单列表
"a" - "Red"
"a" - "Yellow"
"b" - "Blue"
"b" = "Red"
// and so on
然后按值分组并从这些组中构建一个新字典。试试这个代码:
var commonValues = dict.SelectMany(kv => kv.Value.Select(v => new {key = kv.Key, value = v}))
.GroupBy(x => x.value)
.Where(g => g.Count() > 1)
.ToDictionary(g => g.Key, g => g.Select(x => x.key).ToList());
推荐阅读
- python - 根据条件在熊猫数据框行之间填充多行
- python - 为什么 [tag:weasyprint] xhtml-to-pdf 不适合 A4 页面?
- dns - 我应该如何使用路由器作为 DHCP 服务器来宣传运行 pi-hole 和 pivpn 的 pi 服务器的 DNS?
- if-statement - 有没有办法从最后一个条件 x 开始计算?
- java - 使用 Streams 将对象列表转换为地图
- maven - 使用列表过滤 Maven 配置文件
- c# - Net Core:具有通用类 T 和参数的 Moq 方法
- android - 如何使用 gradle kotlin dsl 设置单元测试 jvmargs
- android - 拍照时未调用 ImageReader.OnImageAvailableListener()
- python - 如何修复我的硒代码超时异常错误?