2011-04-06 29 views
1

我需要一個所有孩子的列表。我將如何去獲取只有兒童項目。如何使用linq查詢獲取所有孩子

這裏是我如何讓孩子的

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

回答

4

由於relatedchilds已經是每個父母中的集合,它本身就是一個集合,你可以使用SelectMany()到嵌套集合壓扁成的id的平面集合:

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

或者查詢格式:

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

哇..謝謝你.. – Luke101 2011-04-06 01:18:04