2011-05-31 165 views
5

我的對象包含集合集合。我喜歡獲取所有的子對象ID並將其存儲在一個字符串數組中。LInq查詢收藏集合

MainObject包含父目錄

家長包含兒童名單

兒童屬性(ID,姓名)

我如何可以查詢MainObject並找到所有子ID,並將其存儲在字符串數組使用linq?

回答

11

您可以使用SelectMany

var stringArray = MainObject.ListOfParent 
          .SelectMany(p => p.ListOfChildren 
               .Select(c => c.Id.ToString())) 
          .ToArray() 
+0

由於現在所有的關鍵是..它的工作是用許多選擇 – Bumble 2011-05-31 14:08:03

3
var arrayOfIds = MainObject.ListOfParents 
          .SelectMany(x => x.ListOfChildren) 
          .Select(x => x.Id) 
          .ToArray(); 
+0

感謝所有..它是工作,現在關鍵正在使用select many。 – Bumble 2011-05-31 14:07:18

4

試試這個

var id =parents.SelectMany(p => p.Children).Select(x => x.Id).ToArray();