c# - 使用 LINQ 反转和展平字典
问题描述
我有一些看起来像:
{
"Item1": ["1a", "1b", "1c"],
"Item2": ["2a"],
"Item3": ["3a", "3b"]
}
我想要的是这样的:
{
"1a": "Item1",
"1b": "Item1",
"1c": "Item1",
"2a": "Item2",
"3a": "Item3",
"3b": "Item3"
}
我已经能够做到这一点,但只是想知道是否有更简洁的 LINQ 方式?
Dictionary<string, string[]> items = new Dictionary<string, string[]>(...);
Dictionary<string, string> endResult = new Dictionary<string, string>(); // This is correct
var reversed = items.ToDictionary(x => x.Value, x => x.Key);
foreach (var item in reversed)
{
foreach (var inner in item.Key)
{
endResult.Add(inner, item.Value);
}
}
解决方案
Dictionary<string, string> endResult = items.Select(o => o.Value.Select(v => new { Value = v, Key = o.Key }))
.SelectMany(o => o)
.ToDictionary(o => o.Value, o => o.Key);
推荐阅读
- python-3.x - 将 azure 包安装到 virtualenv 时 Windows 访问被拒绝
- ajax - 通过 AJAX 查询 JSON 响应时如何绕过 Cloudflare 的 DDOS 保护?
- .net - 我需要提供框架和 Nuget 包升级的“证明”
- java - Elasticsearch MAC 10.14.6 with Java jdk-12.0.2.jdk main 错误无法找到 ESJsonLayout 的插件类型
- python - 替换 DataFrame PYTHON 中列内的值
- amazon-web-services - 如何从 Amazon Certificate Manager 下载公共证书
- javascript - 取消后VueJS表单不会恢复到原始状态
- c# - 如何使用 C# 驱动程序替换 mongodb 列表中的元素
- angular - 相对于鼠标位置的角度工具提示指令
- angular - Angular 7:如何重写嵌套订阅?