2

我再次完全陷入了我目前正在开发的用于提高我的 C# 技能的 Windows 窗体项目上。

我需要获得每年薪水增幅最高的职业(返回一个字符串,即 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;
    }

我已经知道如何计算一个职业每年的平均工资增长:

每年的工资增长 = (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 表达式,所以我在语法上苦苦挣扎。

4

2 回答 2

3

您可以使用 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;
于 2013-07-12T01:14:16.793 回答
-1

一条线:

allSalaries.OrderByDescending(s=>(s.CurrentSalary - 
 s.StartSalary)/s.YearOfEmployment).First().Profession
于 2013-07-12T01:41:40.943 回答