如何使用linq查询获得所有子节点

本文关键字:子节点 何使用 linq 查询 | 更新日期: 2023-09-27 17:49:24

我需要一个所有孩子的列表。如何只获取子项呢?

这是我如何得到孩子的

//lets get the parents along with the childs
var parents = from p in context.post
              where p.isDeleted == false && p.userid == new Guid(UserID)
                   let relatedchilds = from c in context.post
                                       where c.id == p.id
                                       select c.id
                   select new
                   {
                        p.id,
                        p.userid,
                        relatedchilds
                   }
//now lets get only the childs in the previous query
var childs = from c in parents
              select new
              {
                   c.relatedchilds.   //This is where my problem is
              }

如何在一列中只获得相关的子节点?

如何使用linq查询获得所有子节点

由于relatedchilds已经是每个父类中的集合,父类本身也是一个集合,因此您可以使用SelectMany()将嵌套集合平铺为id的平面集合:

var childs = parents.SelectMany( p => p.relatedchilds);

查询格式:

var childs = from p in parents
             from child in p.relatedchilds
             select child;