我正在尝试简单的事情,形成一个我希望获得前两名最高员工名单的员工集合。但是请记住,可以有多名员工具有相同的薪水,所以如果他们的薪水范围最大,我希望他们都是。以下是我正在使用的收藏品:
List<Employee> Employees = new List<Employee>
{
new Employee {EmployeeID = 1,EmployeeName ="A", Department ="Dept1", Salary = 10000 },
new Employee {EmployeeID = 5,EmployeeName ="A1", Department ="Dept2", Salary = 12000 },
new Employee {EmployeeID = 2,EmployeeName ="B", Department ="Dept1", Salary = 20000 },
new Employee {EmployeeID = 3,EmployeeName ="C", Department ="Dept1", Salary = 20000 },
new Employee {EmployeeID = 6,EmployeeName ="B1", Department ="Dept2", Salary = 4500 },
new Employee {EmployeeID = 4,EmployeeName="D", Department ="Dept1", Salary = 30000 },
};
和Employee类是:
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Department { get; set; }
public long Salary { get; set; }
}
以下是我的查询:
var result1 = from x in Employees
group x by x.Salary into g
from y in g.OrderBy(x=>x.Salary).Take(2)
select new { y.EmployeeID };
foreach (var item in result1)
{
Console.WriteLine(item.EmployeeID);
}
我在这里要做的是,首先我根据他们的工资对所有员工进行分组。然后使用TAKE扩展方法对这些组进行排序并前两组,然后打印这两组中的所有员工。
但我不知道为什么要打印所有员工;它甚至没有订购它们。有人可以分享一些想法并告诉我这个查询有什么问题吗?
答案 0 :(得分:0)
您可以先选择不同的最高薪水,然后将其加入员工:
var q =
from s in Employees.Select(e => e.Salary).Distinct().OrderByDescending(s => s).Take(2)
from e in Employees.Where(e => e.Salary == s)
select e;