Skip to main content
 首页 » 编程设计

c#之如何使用 linq 查询获取所有 child

2024年02月23日15lyhabc

我需要所有 child 的列表。我将如何只获取子项。

这是我得到 child 的方法

//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 
              } 

如何只获取一列中的相关子项?

请您参考如下方法:

由于 relatedchilds 已经是每个父级中的一个集合,它本身就是一个集合,您可以使用 SelectMany()将嵌套集合展平为 id 的平面集合:

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

或者查询格式:

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