1

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

 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
4

6 回答 6

7

您可以使用:

var massagedEmployees = employees.GroupBy(e => e.Department)
                                .Select(g => new { Department = g.Key, Avg = g.Average(e => e.Salary) } );
于 2013-10-15T17:52:36.677 回答
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)
                                  });
于 2013-10-15T17:52:10.717 回答
2
var massagedEmployees = employees
                       .GroupBy(e => e.Department)
                       .Select(p=> new {p.Key, p.Average(q=>q.Salary)};
于 2013-10-15T17:52:24.097 回答
0
employees.Where(e => e.Department == "[department]")
         .Average(e => e.Salary);
于 2013-10-15T17:54:59.637 回答
0
  var massagedEmployees =
                employees.GroupBy(e => e.Department).Select(c => new {Dep = c.Key, Sum = c.Sum(i => i.Salary)/c.Count()});
于 2013-10-15T17:57:50.967 回答
0

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

employees.GroupBy(e=>e.Department,items=>items.Average(e=>e.Salary))
于 2013-10-15T22:55:21.450 回答