使用linq,我如何创建IEnumerable<>来自另一个IEnumerable<>的属性

时间:2010-11-04 22:31:40

标签: c# linq

我有一个清单:

IEnumerable<Person> people

我希望得到这个:

IEnumerable<Dog> peoplesDogs

其中对象的属性,也是

 IEnumerable<Dog> 

4 个答案:

答案 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)