C# LINQ - 将 children 和 parents 的平面列表映射到分层列表

C# LINQ - Map a flat list of children and parents to a hierarchical list

我将此 LINQ 代码用于 select flat 列表 children 及其来自 SQL 的 parents数据库:

 (from c in _context.Children
  join cp in _context.ChildParents on c.Id equals cp.ChildId
  join p in _context.Parents on cp.ParentId equals p.Id
  select new ChildWithParentFlat()
     {
      ChildId = c.Id,
      ChildName = c.Name,
      ParentId = p.Id,
      ParentName = p.Name
     }
 ).ToList();

它以这种格式显示一个列表:

[
{
    "ChildId": 1,
    "ParentId": 1,
    "ChildName": "FirstChild",
    "ParentName": "FirstParent"
},
{
    "ChildId": 1,
    "ParentId": 2,
    "ChildName": "FirstChild",
    "ParentName": "SecondParent"
},
{
    "ChildId": 2,
    "ParentId": 3,
    "ChildName": "SecondChild",
    "ParentName": "ThirdParent"
},
{
    "ChildId": 2,
    "ParentId": 4,
    "ChildName": "SecondChild",
    "ParentName": "FourthParent"
}
]

我想将此列表转换为分层列表,以便每个 object 将包含一个 child 及其 parents。像这样:

[
{
    "ChildId": 1,      
    "ChildName": "FirstChild",        
    "Parents": [
        {
            "ParentId": 1,
            "ParentName": "FirstParent"
        },
        {
            "ParentId": 2,
            "ParentName": "SecondParent"
        }
    ]
},
{
    "ChildId": 2,
    "Parents": [
        {
            "ChildName": "SecondChild",
            "ParentName": "ThirdParent",
        },
        {
            "ParentId": 4,
            "ParentName": "FourthParent"
        }
    ]
},

]

最好的方法是什么?

I want to convert this list to hierarchical list

使用GroupBy:

var hyrarchical = flatList
   .GroupBy(x => (x.ChildId, x.ChildName))
   .Select(cg => (
       ChildId: cg.Key.ChildId, 
       ChildName: cg.Key.ChildName,
       Parents: cg.GroupBy(x => (x.ParentId, x.ParentName))
                  .Select(pg => (ParentId: pg.Key.ParentId, ParentName: pg.Key.ParentName))) 
   ));

您可以在需要的地方添加 ToList,您也可以使用自定义 class 而不是这些元组,