【问题标题】:Query to count employees and display departments that have more than one employee [closed]查询以统计员工并显示拥有超过一名员工的部门[关闭]
【发布时间】:2019-04-20 06:32:29
【问题描述】:

我需要使用 LINQ 查询以显示所有部门、他们的位置和员工人数,其中员工人数 >1。

我在 Department 模型中有 ICollection 属性。

部门表:

departmentId | departmentLocation
      1             London
      2             Paris
      3             New York

员工表:

employeeId | employeeName |departmentId
      1           John         3
      2           Mary         2
      3           Steve        3

非常感谢。

【问题讨论】:

  • 你有没有尝试过?

标签: c# sql linq asp.net-core


【解决方案1】:

如果您在 Department 模型中有 public virtual ICollection<Employee> Employees { get; set; } 属性,则:

var result = context
                .Department
                .Where(d => d.Employees.Count > 1)
                .Select(d => new
            {
                d.departmentId,
                d.departmentLocation,
                NumberOfEmployees = d.Employees.Count
            }).ToList();

【讨论】:

  • 谢谢一百万,它有效,但给了我所有部门,现在我将尝试只获取员工人数超过 1 的部门。
  • 很高兴它有帮助,您尝试更新的答案了吗?我在更新的答案中添加了Where 方法。
  • 我自己尝试过并在最后添加了“Where(d=> d.NumberOfEmployees>1)”,但您的解决方案看起来更好。
猜你喜欢
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2022-01-19
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多