[英]Filter anonymous type collection
我有一些C#代码,它们创建新的匿名类型(集合)。 集合中的条目仅在Child.Value上有所不同。 我要达到的目的是:通过获取每个父级中每个孩子的最高值的父子对来减少没有子重复的父子对的数量。 子代以子代号区分。
var familyPairs = family
.SelectMany(parent => parent.Children, (parent, child) =>
new {
Parent = parent,
Child = child
})
.OrderByDescending(pair => pair.Child.Value);
如果每个父母都需要一对亲子对,那么可以使用简单选择:
family.Select(p => new {
Parent = p,
Child = p.Children.OrderByDescending(c => c.Value).FirstOrDefault()
})
或者,如果您不希望没有孩子的父母成对,请过滤掉没有孩子的父母:
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 })
如果只需要最大的子项,则排序会浪费时间(子项列表的n log n个操作)。 相反,您应该使用Aggregate()扩展方法对每个子级列表进行一次迭代,以使子级获得最大值。
family.Select(p => new {
Parent = p,
Child = p.Children.Aggregate((c1, c2) => c1.Value > c2.Value ? c1 : c2)})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.