获取与每年最高值增长相关联的字符串

本文关键字:关联 字符串 最高值 获取 | 更新日期: 2023-09-27 18:22:06

我又一次完全陷入了我目前正在开发的Windows窗体项目中,以提高我的C#技能。

我需要得到每年薪水增长最高的职业(返回一个字符串,SalaryInformation对象的职业属性)。

让我展示一下SalaryInformation类的样子:

public sealed class SalaryInformation
{
    private string profession;
    private int yearOfEmployment;
    private decimal startSalary;
    private decimal currentSalary;
    public string Profession
    {
        get { return profession; }
        set { profession = value; }
    }
    public int YearOfEmployment
    {
        get { return yearOfEmployment; }
        set { yearOfEmployment = value; }
    }
    public decimal StartSalary
    {
        get { return startSalary; }
        set { startSalary = value; }
    }

    public decimal CurrentSalary
    {
        get { return currentSalary; }
        set { currentSalary = value; }
    }
    public SalaryInformation()
    { }
    public SalaryInformation(string p, int yoe, decimal startS, decimal currentS)
    {
        profession = p;
        yearOfEmployment = yoe;
        startSalary = startS;
        currentSalary = currentS;
    }

我已经知道如何计算一个职业每年的平均加薪幅度:

salaryIncrease per year=(totalCurrentSalaries-totalStartingSalaries)/totalYears;

现在我的方法代码如下:

 private string GetProfessionWithHighestSalaryIncrease()
    {
        List<SalaryInformation> allSalaries = new List<SalaryInformation>();
        allSalaries = data.GetSalaryInformation();
        //Here I got stuck. I think that this could be solved in a single linq query.
        //But since I have to make a calculation of EVERY salaryincrease of EVERY
        //profession, I keep getting stuck on how I should solve this.
        //After all, I need the sum of every professions CurrentSalaries, the sum
        //of every professions StartingSalaries and the sum of every professions
        //yearOfEmployment to be able to calculate that professions salaryincrease
        //per year.
        //The profession(string) with the highest salary increase per year, has to  be returned.

    }

我确信这可以在单个组合的Linq/lambda表达式查询中解决。但我不习惯写linq和lamdba表达式,所以我在语法上很吃力。

获取与每年最高值增长相关联的字符串

您可以使用group-by对集合进行分区,然后按平均工资增长排序,并取第一个:

string maxSalaryProfession = allSalaries
    // group by profession
    .GroupBy(info => info.Profession)
    // order rows by the average salary increase per profession
    .OrderByDescending(prof => 
        (prof.Sum(info => info.CurrentSalary) - prof.Sum(info => info.StartSalary))
            / prof.Sum(info => info.YearOfEmployment)
     )
     .First().Key;

一行:

allSalaries.OrderByDescending(s=>(s.CurrentSalary - 
 s.StartSalary)/s.YearOfEmployment).First().Profession