开发者

using linq, how can i create a IEnumerable<> from a property of another IEnumerable<>

开发者 https://www.devze.com 2023-01-23 08:37 出处:网络
i have a list: IEnumerable<Person> people and i want to get this: IEnumerable<Dog> peoplesDogs

i have a list:

IEnumerable<Person> people

and i want to get this:

IEnumerable<Dog> peoplesDogs

where Dogs is a property of a person object and also a

 IEnu开发者_C百科merable<Dog> 


var peoplesDogs = people.SelectMany(p => p.Dogs);


var peoplesDogs = from p in people 
                  from d in p.Dogs
                  select d;


var peopleDogs = people.Select(p => p.Dogs)

Edit

The above would create an IEnumerable<IEnumerable<Dog>> but apparently what is needed is just IEnumerable<Dog>.

As in LukeH's answer, you need to use SelectMany to flatten:

var peopleDogs = people.SelectMany(p => p.Dogs)


you can also do

var peoplesDogs = from p in people
                  from d in p.Dogs
                  select d;

which has the same effect as:

var peoplesDogs = people.SelectMany(p => p.Dogs)
0

精彩评论

暂无评论...
验证码 换一张
取 消