LINQ - 获取列表中列表中的所有项目?

[英]LINQ - Get all items in a List within a List?


I'm currently working my way through the learning curve that is LINQ and I could really use some assistance. I don't know if what I want is possible, but if I had to wager, I bet it is.

我正在努力学习LINQ的学习曲线,我真的可以使用一些帮助。我不知道我想要的是否可能,但如果我不得不下注,我敢打赌。

I currently have a list of objects called _tables and each of these objects has within it another list of objects exposed through the property, "Indexes". Essentially, I'd like to end up with one List that contains all the Indexes from all of the _tables.

我目前有一个名为_tables的对象列表,其中每个对象都有一个通过属性“索引”公开的另一个对象列表。基本上,我想最终得到一个List,其中包含来自所有_tables的所有索引。

Here's what I have so far:

这是我到目前为止所拥有的:

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

Unfortunately, this seems to be giving me another List of Lists, but only where the Indexes List contains more than one value... Is there some way to get all of these lists together without loops?

不幸的是,这似乎给了我另一个列表列表,但只有索引列表包含多个值...有没有办法将所有这些列表放在一起没有循环?

4 个解决方案

#1


38  

You want to use the SelectMany extension method.

您想使用SelectMany扩展方法。

_tables.SelectMany(t => t.Indexes)

#2


6  

In addition to tbischel's answer, the query expression version of what you're going for is below.

除了tbischel的答案之外,您要查找的查询表达式版本如下。

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

#3


4  

You don't need the where clause and you also shouldn't need to tell it what tab is

您不需要where子句,也不需要告诉它是什么选项卡

And you will need to use SelectMany

你需要使用SelectMany

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

Or you could do it like this

或者你可以这样做

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

That should be a little more familiar syntaz

这应该是一个更熟悉的syntaz

#4


2  

var rows = from item in table select item;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/07/16/fa8ad4cf22d1ad6ad22ab6c886f0c0bd.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号