过滤匿名类型集合

Filter anonymous type collection

我有一些 C# 代码可以创建新的匿名类型(集合)。集合中的条目仅相差 Child.Value。我想要实现的是:通过在每个 children 中获取具有最高值的 parent-child 对来减少没有 child 重复的 parent-child 对的数量 parent。 children 由 child Id 区分。

var familyPairs = family
        .SelectMany(parent => parent.Children, (parent, child) => 
               new { 
                    Parent = parent, 
                    Child = child
                   })
        .OrderByDescending(pair => pair.Child.Value);

如果每个 parent 需要单个 parent-child 对,那么您可以使用简单的 select:

 family.Select(p => new { 
     Parent = p, 
     Child = p.Children.OrderByDescending(c => c.Value).FirstOrDefault()
 })

或者如果您不想 parents 没有 children - 过滤掉 child 免费 parents:

 family.Where(p => p.Children.Any()).Select(p => new { 
     Parent = p, 
     Child = p.Children.OrderByDescending(c => c.Value).First()
 })

更新后发现您需要 SelectMany,但您需要按 ID 对 children 进行分组,并且每个组 child 中的 select 具有最大值:

 family.SelectMany(
   p => p.Children.GroupBy(c => c.Id)
                  .Select(g => g.OrderByDescending(c => c.Value).First()),
   (p,c) => new { Parent = p, Child = c })

如果你只想要最大值child,排序是浪费时间(children的列表n log n次操作)。相反,您应该使用 Aggregate() 扩展方法遍历 children 的每个列表一次,以获得具有最大值的 child。

family.Select(p => new { 
 Parent = p, 
 Child = p.Children.Aggregate((c1, c2) => c1.Value > c2.Value ? c1 : c2)})

参见:How can I get LINQ to return the object which has the max value for a given property?