我想加入两个对象并将它们组合成一个并使用LINQ执行平均查询。以下是我的课程
public class emp
{
public int empID { get; set; }
public string empName { get; set; }
}
public class salaries
{
public int empID { get; set; }
public string month { get; set; }
public int salary { get; set; }
}
public void repository()
{
lstemp = new List<emp> {
new emp{empID=1,empName="A"},
new emp{empID=2,empName="B"},
new emp{empID=3,empName="C"}
};
lstsalary = new List<salaries> {
new salaries{empID=1,month="jan",salary=1000},
new salaries{empID=1,month="feb",salary=1500},
new salaries{empID=1,month="mar",salary=2000},
new salaries{empID=2,month="jan",salary=1500},
new salaries{empID=2,month="feb",salary=2000},
new salaries{empID=3,month="jan",salary=1500},
new salaries{empID=3,month="feb",salary=2000},
new salaries{empID=3,month="mar",salary=2000},
new salaries{empID=3,month="apr",salary=2000},
};
}
static void Main()
{
new calculator().repository();
var result = from e in calculator.lstemp
join
s in calculator.lstsalary on e.empID equals s.empID
group s by s.empID into grp
select new {
salary = (from g in grp where g.empID == grp.Key select g.salary).Average()
};
}
现在从上面的数据我想根据empID进行分组,然后我想从他们各自的薪水中取平均值。
结果应该是empName和平均工资 雇员。
如何实现这一目标。 谢谢。
答案 0 :(得分:2)
您可以将这两个对象存储为匿名类型,以访问您也可以按属性,ID和名称分组的empName:
var result = from e in calculator.lstemp
join s in calculator.lstsalary on e.empID equals s.empID
let empSal = new { emp = e, sal = s }
group empSal by new { empSal.emp.empID, empSal.emp.empName } into g
select new
{
empName = g.Key.empName,
salary = g.Average(x => x.sal.salary)
};