我有一个清单:
IEnumerable<Person> people
我希望得到这个:
IEnumerable<Dog> peoplesDogs
其中狗是人对象的属性,也是
IEnumerable<Dog>
答案 0 :(得分:6)
var peoplesDogs = people.SelectMany(p => p.Dogs);
答案 1 :(得分:1)
var peoplesDogs = from p in people
from d in p.Dogs
select d;
答案 2 :(得分:0)
var peopleDogs = people.Select(p => p.Dogs)
修改强>
上面会创建一个IEnumerable<IEnumerable<Dog>>
,但显然需要的只是IEnumerable<Dog>
。
在LukeH的回答中,您需要使用SelectMany
来展平:
var peopleDogs = people.SelectMany(p => p.Dogs)
答案 3 :(得分:0)
你也可以
var peoplesDogs = from p in people
from d in p.Dogs
select d;
具有与以下相同的效果:
var peoplesDogs = people.SelectMany(p => p.Dogs)