创建父级 - >两个集合中的子层次结构

时间:2016-10-29 09:38:25

标签: c# linq .net-4.5 linq-to-objects

我有两个单独的集合实例,其中包含数据

List<Parent> parents;
List<Child> children;

可以通过Child.ParentId和Parent.Children连接两个集合。

父集合没有填充子属性,那么如何将Parent对象与Children链接?

2 个答案:

答案 0 :(得分:1)

试试这个:

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();  
}

答案 1 :(得分:1)

 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();