2010-07-16 125 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; 
相关问题