我再次完全陷入了我正在开发的用于提高我的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表达式,所以我在语法上苦苦挣扎。
答案 0 :(得分: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;
答案 1 :(得分:-1)
一行:
allSalaries.OrderByDescending(s=>(s.CurrentSalary -
s.StartSalary)/s.YearOfEmployment).First().Profession