简体   繁体   English

过滤匿名类型集合

[英]Filter anonymous type collection

I have some little C# code which creates new anonymous type (collection). 我有一些C#代码,它们创建新的匿名类型(集合)。 Entries in the collection differ only by Child.Value. 集合中的条目仅在Child.Value上有所不同。 What i am trying to achieve is: reduce the count of the parent-child pairs without child duplicates by getting the parent-child pairs with the highest value for each children in every parent. 我要达到的目的是:通过获取每个父级中每个孩子的最高值的父子对来减少没有子重复的父子对的数量。 The children are distinguished by child Id. 子代以子代号区分。

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

If you need single parent-child pair for each parent, then you can use simple select: 如果每个父母都需要一对亲子对,那么可以使用简单选择:

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

Or if you don't want pairs for parents without children - filter out child free parents: 或者,如果您不希望没有孩子的父母成对,请过滤掉没有孩子的父母:

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

After your update it turns out that you need SelectMany, but you need to group children by id and select from each group child with max value: 更新后,事实证明您需要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 })

If you want only the maximum child, sorting is a waste of time (n log n operations for the list of children). 如果只需要最大的子项,则排序会浪费时间(子项列表的n log n个操作)。 Instead, you should use the Aggregate() extension method to iterate through each list of children once to get the child with the maximum value. 相反,您应该使用Aggregate()扩展方法对每个子级列表进行一次迭代,以使子级获得最大值。

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

See: How can I get LINQ to return the object which has the max value for a given property? 请参阅: 如何使LINQ返回具有给定属性最大值的对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM