【问题标题】:Create a parent -> children hierarchy from two collections从两个集合创建父级 -> 子级层次结构
【发布时间】:2017-03-12 02:19:17
【问题描述】:

我有两个单独的集合实例,其中填充了数据

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

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

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

【问题讨论】:

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


    【解决方案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();  
    }
    

    【讨论】:

    • 您好,感谢您的快速回复。需要说明的是,这是一个左连接操作,没有孩子的父母还会在场吗?
    • 这是分组连接,当我们想要分层数据结构时使用它,是的,没有孩子的父母会出现。
    【解决方案2】:
     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();
    

    【讨论】:

    • @goran- 这段代码只会给我父数据吗?基于连接,这会提供层次结构吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多