过滤匿名类型集合

时间:2017-02-20 17:05:24

标签: c# linq collections anonymous-types

我有一些小的C#代码,可以创建新的匿名类型(集合)。集合中的条目仅由Child.Value不同。我想要实现的目标是:通过为每个父级中的每个子级获取具有最高值的父子对,减少没有子级重复的父子对的计数。孩子们以孩子Id为特色。

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

2 个答案:

答案 0 :(得分:2)

如果每个父母都需要单亲父子对,那么您可以使用简单的选择:

seasonal.model %>% 
      group_by(year, season) %>% 
      summarize(anom = (lsmean - mean(lsmean))/sd(lsmean))

或者,如果你不想为没有孩子的父母配对 - 过滤掉没有孩子的父母:

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

更新后,事实证明您需要SelectMany,但您需要按ID对儿童进行分组,并从具有最大值的每个儿童群组中进行选择:

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

答案 1 :(得分:2)

如果只想要最大子项,则排序是浪费时间(对于子项列表,n log n operation)。相反,您应该使用Aggregate()扩展方法迭代每个子项列表一次,以获得具有最大值的子项。

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?