我有一些创建新匿名类型(集合)的 C# 代码。集合中的条目仅在 Child.Value 上有所不同。我想要实现的是:通过为每个 parent 中的每个 child 获取最高值的父子对来减少没有子重复的父子对的数量。 children 通过 child Id 来区分。
var familyPairs = family
.SelectMany(parent => parent.Children, (parent, child) =>
new {
Parent = parent,
Child = child
})
.OrderByDescending(pair => pair.Child.Value);
请您参考如下方法:
如果每个 parent 都需要一对父子,那么您可以使用简单的选择:
family.Select(p => new {
Parent = p,
Child = p.Children.OrderByDescending(c => c.Value).FirstOrDefault()
})
或者,如果您不想为没有 child 的 parent 配对 - 过滤掉没有 child 的 parent :
family.Where(p => p.Children.Any()).Select(p => new {
Parent = p,
Child = p.Children.OrderByDescending(c => c.Value).First()
})
更新后发现您需要 SelectMany,但您需要按 id 对子项进行分组并从每个组中选择具有最大值的子项:
family.SelectMany(
p => p.Children.GroupBy(c => c.Id)
.Select(g => g.OrderByDescending(c => c.Value).First()),
(p,c) => new { Parent = p, Child = c })
