2010-07-16 209 views
17

我目前正在學習LINQ的學習曲線,我真的可以使用一些幫助。我不知道我想要的是否可能,但如果我必須下注,我敢打賭。LINQ - 獲取列表中列表中的所有項目?

我目前有一個名爲_tables的對象列表,其中的每個對象都有另一個通過屬性「Indexes」公開的對象列表。實質上,我想最終得到一個包含所有_tables所有索引的List。

這是我到目前爲止有:

var indexes = from TableInfo tab 
       in _tables 
       where tab.Indexes.Count > 0 
       select tab.Indexes; 

不幸的是,這似乎是給我列出的另一個列表,但只有在索引列表中包含多個值...有沒有一些方法來把所有這些列表放在一起,不用循環?

回答

34

您想使用SelectMany擴展方法。

_tables.SelectMany(t => t.Indexes) 
+0

只讀:http://community.bartdesmet.net/blogs/bart/archive/2008/08/19/probably-the-most-powerful-linq-operator-selectmany.aspx – 2010-07-16 16:54:26

5

除了tbischel的回答之外,您要查詢的查詢表達式版本如下。

var indexes = from TableInfo tab in _tables 
       from index in tab.Indexes 
       select index; 
4

不需要where子句,你也不應該需要告訴它什麼標籤是

而且你將需要使用的SelectMany

var indexes = (from tab in _tables).SelectMany(t => t.Indexes) 

或者你可以做像這樣

var indexes = from tab in _tables 
        from t in tab.Indexes 
        select t; 

這應該是一個小更熟悉syntaz

2
var rows = from item in table select item; 
相關問題