从两个集合创建父 -> 子层次结构
Create a parent -> children hierarchy from two collections
我有两个单独的集合实例,其中填充了数据
List<Parent> parents;
List<Child> children;
可以通过 Child.ParentId 和 Parent.Children.
连接两个集合
parents 集合没有 Children 属性 填充,所以我如何 link Parent objects with Children?
试试这个:
var result = from d in parents
join s in children
on d.ParentID equals s.ParentID into g
select new
{
ParentName = d.ParentName,
ChildList = g
};
foreach (var item in result)
{
Console.WriteLine("Parent: {0}", item.ParentName);
foreach (var Child in item.ChildList)
{
Console.WriteLine(Child.Name);
}
Console.WriteLine();
}
children.Join(parents,
c => c.ParentId,
p => p.ParentId,
(c, p) => new { children = c, parents = p })
.Select(x => x.parents).ToList();
更新
var result = parents.Join(children,
p => p.ParentId,
c => c.ParentId,
(p,c) => new { parents = p,children = c })
.Select(x => new
{
ParentName = x.parents.ParentName,
ChildList= x.children
})
//.GroupBy(x=>x.ParentName )
.ToList();
我有两个单独的集合实例,其中填充了数据
List<Parent> parents;
List<Child> children;
可以通过 Child.ParentId 和 Parent.Children.
连接两个集合parents 集合没有 Children 属性 填充,所以我如何 link Parent objects with Children?
试试这个:
var result = from d in parents
join s in children
on d.ParentID equals s.ParentID into g
select new
{
ParentName = d.ParentName,
ChildList = g
};
foreach (var item in result)
{
Console.WriteLine("Parent: {0}", item.ParentName);
foreach (var Child in item.ChildList)
{
Console.WriteLine(Child.Name);
}
Console.WriteLine();
}
children.Join(parents,
c => c.ParentId,
p => p.ParentId,
(c, p) => new { children = c, parents = p })
.Select(x => x.parents).ToList();
更新
var result = parents.Join(children,
p => p.ParentId,
c => c.ParentId,
(p,c) => new { parents = p,children = c })
.Select(x => new
{
ParentName = x.parents.ParentName,
ChildList= x.children
})
//.GroupBy(x=>x.ParentName )
.ToList();