leora
leora

Reputation: 196499

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

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

 IEnumerable<Dog> 

Upvotes: 1

Views: 286

Answers (4)

Mark Heath
Mark Heath

Reputation: 49482

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)

Upvotes: 0

devuxer
devuxer

Reputation: 42364

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)

Upvotes: 0

LukeH
LukeH

Reputation: 269368

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

Upvotes: 6

John Sheehan
John Sheehan

Reputation: 78104

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

Upvotes: 1

Related Questions