簡體   English   中英

使用linq,如何從另一個IEnumerable <>的屬性創建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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM