[英]How can I use LINQ to select a property inside of an IEnumerable that's inside another IEnumerable?
[英]using linq, how can i create a IEnumerable<> from a property of another IEnumerable<>
我有一個清單:
IEnumerable<Person> people
我想得到這個:
IEnumerable<Dog> peoplesDogs
狗是人對象的財產,也是
IEnumerable<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)
編輯
上面的代碼將創建IEnumerable<IEnumerable<Dog>>
但顯然只需要IEnumerable<Dog>
。
就像在LukeH的答案中一樣,您需要使用SelectMany
來展平:
var peopleDogs = people.SelectMany(p => p.Dogs)
你也可以
var peoplesDogs = from p in people
from d in p.Dogs
select d;
具有與以下相同的效果:
var peoplesDogs = people.SelectMany(p => p.Dogs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.