使用LINQ查找部门的平均工资

时间:2013-10-15 17:50:39

标签: c# linq

如何找到每个部门的平均工资?

 var employees = new List<Employee>
                {
                    new Employee {Name = "Tom", Age = 32,Department = "Design",Salary=120000},
                    new Employee {Name = "John", Age = 22,Department = "UI",Salary=86000},
                    new Employee {Name = "Sandra", Age = 36,Department = "UI",Salary=83000},
                    new Employee {Name = "Julie", Age = 54,Department = "Javascript",Salary=80000},
                    new Employee {Name = "Samantha", Age = 21,Department = "Design",Salary=125000}
                };

var massagedEmployees = employees.GroupBy(e => e.Department).Select(g=>g.??????

在SQL中我会做类似

的事情
select Department,avg(salary) from Employees group by Department

6 个答案:

答案 0 :(得分:6)

var massagedEmployees = employees.GroupBy(e => e.Department)
                                 .Select(g=>g.Average(x=>x.Salary));

您应该像这样包含Department key

var massagedEmployees = employees.GroupBy(e => e.Department)
                                 .Select(g=> 
                                   new {
                                      Department = g.Key,
                                      SalaryAvg = g.Average(x=>x.Salary)
                                  });

答案 1 :(得分:6)

您可以使用:

var massagedEmployees = employees.GroupBy(e => e.Department)
                                .Select(g => new { Department = g.Key, Avg = g.Average(e => e.Salary) } );

答案 2 :(得分:2)

var massagedEmployees = employees
                       .GroupBy(e => e.Department)
                       .Select(p=> new {p.Key, p.Average(q=>q.Salary)};

答案 3 :(得分:0)

employees.Where(e => e.Department == "[department]")
         .Average(e => e.Salary);

答案 4 :(得分:0)

  var massagedEmployees =
                employees.GroupBy(e => e.Department).Select(c => new {Dep = c.Key, Sum = c.Sum(i => i.Salary)/c.Count()});

答案 5 :(得分:0)

实际上,您可以将其简化为单个运算符,这与以前的GroupBy答案不同,GroupBy只是为此重载,因此您不需要以下选择:

employees.GroupBy(e=>e.Department,items=>items.Average(e=>e.Salary))