c# - 将字典从 <Parent, IEnumerable<Child>> 反转为 <Child, IEnumerable<Parent>>

标签 c# linq

给定一个可枚举的 Parent,其中每个条目都包含一个 IEnumerableChild 对象

IEnumerable<KeyValuePair<Parent, IEnumerable<Child>>>

我想反转它,所以它是 ChildIEnumerable,其中每个条目都包含 ParentIEnumerable > 对象。

IEnumerable<KeyValuePair<Child, IEnumerable<Parent>>>

最佳答案

source
    .SelectMany(
        x => x.Value,
        (k, v) => new
        {
            Child = k.v,
            Parent = k.Key
        })
    .GroupBy(
        keySelector: x => x.Child,
        elementSelector: x => x.Parent)
    .ToDictionary(
        keySelector: x => x.Key,
        elementSelector: x => x.AsEnumerable());

关于c# - 将字典从 <Parent, IEnumerable<Child>> 反转为 <Child, IEnumerable<Parent>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68420274/

相关文章:

c# - 获取值作为 DateTime,但在 DropDownList 中显示为 DateTime.Year(使用 LINQ)

c# - Windows 服务是否是 "correct"与必须运行 Windows 的嵌入式系统上的硬件交互的选择?

c# - 如何告诉 NewtonSoft.Json.JsonConvert 将枚举序列化为字符串而不是 int

c# - 给定 x,y 点,如何获取前景窗口中不存在的控件的窗口句柄?

c# - 如何使用 HTMLAgilityPack 单独删除 html 标签而不是内部 html 或子标签?

c# - 比较数组或其他方法

c# - 可扩展的 WPF 应用程序 - MEF、MAF 或简单加载?

c# - linq-to-sql 或 linq 在什么时候向数据库发送请求

c# - 如何使用 LINQ to Entities 获取字节数组长度?

c# - 如何在 LINQ 查询中添加静态