我有一个列表:使用LINQ,我怎样才能从其他的IEnumerable <>的属性创建的IEnumerable <>
IEnumerable<Person> people
,我想这一点:
IEnumerable<Dog> peoplesDogs
其中狗是人对象的属性,也是一个
IEnumerable<Dog>
我有一个列表:使用LINQ,我怎样才能从其他的IEnumerable <>的属性创建的IEnumerable <>
IEnumerable<Person> people
,我想这一点:
IEnumerable<Dog> peoplesDogs
其中狗是人对象的属性,也是一个
IEnumerable<Dog>
var peoplesDogs = people.SelectMany(p => p.Dogs);
var peopleDogs = people.Select(p => p.Dogs)
编辑
以上将创建一个IEnumerable<IEnumerable<Dog>>
但显然我们需要的仅仅是IEnumerable<Dog>
。
正如LukeH的答案,你需要使用SelectMany
扁平化:
var peopleDogs = people.SelectMany(p => p.Dogs)
var peoplesDogs = from p in people
from d in p.Dogs
select d;
他改变了问题 – 2010-11-04 22:35:01
@John:够公平的......一定是快的:) – 2010-11-04 22:36:01
我可以让我的两点回来吗?除非这一个也被打破,我猜测 – 2010-11-04 22:36:33
,你也可以做
var peoplesDogs = from p in people
from d in p.Dogs
select d;
具有相同的效果:
var peoplesDogs = people.SelectMany(p => p.Dogs)
-1出于同样的原因,约翰希恩的回答原本是错误的。这需要根据LukeH的回答和John Sheehan的回答,一般用SelectMany进行扁平化。我知道这是由于编辑问题,但目前的问题仍然存在错误 - 我建议删除它。 – 2010-11-04 22:35:10
原来的问题没有说明它也是IEnumerable – 2010-11-04 22:35:57