[英]Joining parent and child collection in LINQ for a single merged output
I have a collection of items which each contain a secondary collection. 我有一个项目集合,每个项目都包含一个辅助集合。 I need to generate a list of new items based off the total set of secondary items.
我需要根据次要项目的总集生成新项目列表。 Eg if you have a list of dogs and each dog has a list of friends, I need a total list of all dog friends for all dogs.
例如,如果你有一个狗列表,每只狗有一个朋友列表,我需要所有狗的所有狗朋友的总清单。
Normally I would do this with SelectMany but the difficulty here is my secondary objects do not contain a reference back to the parent object, and the new list needs to contain fields from both secondary and parent objects. 通常我会使用SelectMany执行此操作,但这里的难点是我的辅助对象不包含对父对象的引用,并且新列表需要包含来自辅助对象和父对象的字段。 ie as below
即如下
var dogs = List<Dog>
var newList = dogs.SelectMany(i => i.DogFriends).Select(dogFriend => new NewObject
{
fieldOne = dog.propertyOne,
fieldTwo = dog.propertyTwo
fieldThree = dogFriend.propertyOne
});
In the above, I have no reference to dog however, so I cannot select those. 在上面,我没有提到狗,所以我不能选择那些。
What I'm looking for is a way to do a join on the two tables as in SQL, so you can select values from both objects. 我正在寻找的是一种在SQL中连接两个表的方法,因此您可以从两个对象中选择值。 But I want the total values to match the total number of child objects.
但我希望总值与子对象的总数相匹配。 Ie if you have 3 dogs with 3 friends each, the final list will have 9 objects.
即如果你有3只狗,每只3个朋友,最终列表将有9个对象。
How can I achieve this with LINQ? 如何使用LINQ实现这一目标?
Indeed .SelectMany(...)
is the answer. 确实
.SelectMany(...)
就是答案。 Another usage is: 另一种用法是:
var data = dogs
.SelectMany(d => d.DogFriends.Select(df => new { d, df })
.Select(x =>
// Now you can use both d and df
new NewObject {
fieldOne = x.d.propertyOne,
fieldTwo = x.d.propertyTwo
fieldThree = x.df.propertyOne
}
)
.ToArray();
Even simpler is to use the query LINQ notation. 更简单的是使用查询LINQ表示法。 This basically translates to the above at compile time.
这基本上在编译时转换为上述内容。
var data = from d in dogs
from df in d.DogFriends
select new NewObject {
fieldOne = d.propertyOne,
fieldTwo = d.propertyTwo
fieldThree = df.propertyOne
}
使用.SelectMany重载https://msdn.microsoft.com/en-us/library/bb534631%28v=vs.110%29.aspx
var query = petOwners .SelectMany( petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName } )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.