2017-02-20 98 views
1

我有一些创建新的匿名类型(集合)的小C#代码。集合中的条目仅与Child.Value有所不同。我想实现的目标是:通过获取每个父项中每个子项的最高值的父子对,减少没有子项重复项的父子对的计数。孩子是由孩子ID区分。筛选匿名类型集合

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

回答

2

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

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 }) 
+0

我会尝试一下。 :) –

+0

对不起,我编辑我的问题,如果你出来一些关于编辑。但我仍然要试试这个:) –

+0

@CeylanMumunKocabaş从你的编辑中不清楚 - 如果你在父母的孩子列表中有几个同样的孩子,你怎么区分两个不同的孩子? –

2

如果你只想要孩子最大,排序是在浪费时间(N日志N操作为孩子的列表)。相反,您应该使用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?

+0

另外,我应该指出,如果多个孩子分享最大值,则>和> =运算符之间存在很大差异。 >运算符将选择最大值的最后一个孩子,>> =将选择第一个孩子。 – plushpuffin