如何使用linq查询获取所有孩子

时间:2011-04-06 00:20:43

标签: c# linq linq-to-entities

我需要一份所有孩子的清单。我如何才能获得儿童用品。

这是我如何得到孩子的

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

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

1 个答案:

答案 0 :(得分:4)

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

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

或者以查询格式:

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