2013-10-24 61 views
1

我有一個包含多個嵌套集合的模型。例如...在LINQ中列出深層嵌套的子實體

My Sales Record 
    Contains a collection of Customers 
    Each Customer contains a collection of Orders 
     Each Order contains a collection of Items 

我希望能夠創建一個與銷售記錄相關的所有項目的列表,而不會導致編寫嵌套的foreach循環。我試過...

var items = SalesRecord.SelectMany(r => r.Customers) 
       .SelectMany(c => c.Orders) 
       .Select(o => o.Items); 

但這不起作用。

這在LINQ中可以實現嗎?需要

+0

'SelectMany'不會顯示結果直到你實際循環結果集。你在做這個嗎? –

回答

2

還有一個的SelectMany:

var items = SalesRecord.Customers // simply select customers from record 
       .SelectMany(c => c.Orders) 
       .SelectMany(o => o.Items); // here 

你需要扁平化的結果,否則,你將有項目的集合集合。另外,如果您需要項目列表,請不要忘記在查詢結束時致電ToList()

+0

這就是所有與任何銷售記錄無關的項目 – Servy

+1

@Servy在此上下文中只有一個銷售記錄:'SalesRecord'。 –

+0

@Servy,這就是所有銷售記錄的項目 –

0

使用Select每個銷售記錄映射到一個包含記錄,以及項目該記錄的扁平列表,使用多次打電話給SelectMany一個項目:

var items = SalesRecord.Select(record => new 
{ 
    record, 
    Items = record.Customers 
     .SelectMany(c => c.Orders) 
     .SelectMany(o => o.Items), 
}); 
+1

應該是'record.Customers' –

+0

@TimS。確實應該。 – Servy

+0

@TimS。複製粘貼真的讓我今天。在早期版本中是正確的。謝謝。 – Servy