请看下面的例子。这里的 Employee ID =2 aka Steve 有 3 个重复项。 我只想要每个 ID 的一个记录。我想选择薪水第二高的记录。因此,如果是史蒂夫,选择将是工资为 160 的两个史蒂夫帽子之一。
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public static List<Employee> GetAllEmployees()
{
return new List<Employee>()
{
new Employee { ID = 1, Name = "Mark", Salary = 100 },
new Employee { ID = 2, Name = "Steve", Salary = 150 },
new Employee { ID = 2, Name = "Steve", Salary = 160 },
new Employee { ID = 2, Name = "Steve", Salary = 160 },
new Employee { ID = 2, Name = "Steve", Salary = 165 },
new Employee { ID = 3, Name = "Ben", Salary = 140 }
};
}
}
期望的输出:
1 Mark 100
1 Steve 160 //2nd highest salary of steve( there are two such steves so pick any)
1 Mark 100
1 Ben 140
我知道如何根据属性获取不同的记录:
var result = Employee.GetAllEmployees().GroupBy(x=>x.ID).Distinct();
但我在另一边迷路了。
请注意,我只是在寻找 LINQ lambda/扩展语法答案。谢谢!
最佳答案
一种方法是在GroupBy
之后使用Select
。这会将每个组转变为一名员工。
Employee.GetAllEmployees().GroupBy(x=>x.ID).Select(x => FindSecondHighest(x));
FindSecondHighest
应该是这样的:
private static Employee FindSecondHighest(IEnumerable<Employee> employees) {
var list = employees.ToList();
if (list.Count == 1) { return list[0]; }
return list.OrderByDescending(x => x.Salary).Skip(1).First();
}
如果愿意,您可以将方法重写为 lambda,但我觉得这样可读性更好。
编辑:
我意识到,如果有两个最高薪水,这实际上并没有获得第二高薪水。要实际获得第二高的薪水,您可以使用第二个 GroupBy
:
private static Employee FindSecondHighest(IEnumerable<Employee> employees) {
var list = employees.ToList();
if (list.Count == 1) { return list[0]; }
return list.GroupBy(x => x.Salary).OrderByDescending(x => x.Key).Skip(1).First();
}
关于c# - 如何根据 ID 从员工薪水第二高的员工集合中选择具有 LINQ 的不同员工?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55277888/