开发者

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

 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜