【发布时间】:2020-05-23 16:21:43
【问题描述】:
我目前正在开发一个 .NET 4.7 应用程序。
Given 是 1 list,其中包含父元素和子元素。我需要根据父元素 ID 对列表中的所有元素进行分组。
这不是那么简单,因为我有一个复杂的类型对象:List<LinkParentChildViewModel>
public class LinkParentChildViewModel
{
public Location Parent { get; set; }
public List<LocationLink> Children { get; set; }
}
public class Location
{
public int Id { get; set; }
public string Name { get; set; }
}
public class LocationLink
{
public int Id { get; set; }
public int ParentId { get; set; }
public int ChildId { get; set; }
}
好吧,给定的 List 可以包含多个具有相同 Id 但不同 Child 的 Parent 元素。
目前我需要在一个父元素下加入/分组所有具有相同父元素的子元素。
我开始了我的 LINQ 查询,但不知何故我卡住了:
var joined = (from a in LinksParentChild
join b in LinksParentChild
on a.Parent.Id equals b.Parent.Id
select new LinkParentChildViewModel { Parent = a.Parent, Children = new List<LocationLink>
{
// ...
} }).ToList();
你知道如何将列表的所有子元素与相同的父元素分组吗?
非常感谢!!
【问题讨论】: