【问题标题】:How to sum a field for all records and then return the max of all summed records with Linq如何对所有记录的字段求和,然后使用 Linq 返回所有求和记录的最大值
【发布时间】:2017-02-15 16:37:31
【问题描述】:

在所有记录被分组然后求和之后,我试图返回具有最大值的记录。我能够得到总和,但不能返回最大值的完整记录。

这是我目前所拥有的,我将如何获得最大总和值?

from es in EmployeeSkills
group es by es.Employee.FirstName + " " + es.Employee.LastName into empGroup
select new
{
    Name = empGroup.Key,
    YOE = (from y in empGroup select y.YearsOfExperience).Sum ()
}

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你可以使用Aggregate扩展方法

    var query=from es in EmployeeSkills
              group es by es.Employee.FirstName + " " + es.Employee.LastName into empGroup
              select new
              {
                Name = empGroup.Key,
                YOE = empGroup.Select(y=>y.YearsOfExperience).Sum()
              };
    
    var result=query.Aggregate((seed, current)=>current.YOE>seed.YOE?current:seed);
    

    或者你也可以使用MoreLinq库中的MaxBy扩展方法:

    var result=query.MaxBy(e=>e.YOE);
    

    【讨论】:

    • 我认为你有一个错字。你有e 的地方应该是current
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多