简体   繁体   English

使用 LINQ/Lambda 查找员工的第 N 个最高薪水

[英]Find the N-th highest salary of employee using LINQ/Lambda

Hi I used sequential Linq for getting nth highest salary from employee like嗨,我使用顺序 Linq 从员工那里获得第 n 高的薪水

    var ThirdHighestSal = from vr in Employee.getAllEmployee()
                 group vr by vr.Salary into gr
                 orderby gr.Key descending
                 select( new {salary=gr.OrderBy(x=>x.Salary).Skip(2).First()});
        foreach (var sal in ThirdHighestSal)
        {
            Console.WriteLine("3rd highest sal is {0}",sal.salary);
        }

when i execute this it is throwing exception like当我执行它时,它会抛出异常

Sequence contains no elements(InvalidOperationException was unhadled)序列不包含任何元素(InvalidOperationException 未处理)

Can anyone help me on that query please?有人可以帮我解决这个问题吗?

use FirstOrDefault instead of First and you will get a null object if no element could be found.使用 FirstOrDefault 而不是 First ,如果找不到元素,您将得到一个 null object 。

With lamda you could write:使用 lamda 你可以这样写:

 var ThirdHighestSal = Employee.getAllEmployee().Select(x => x.Salary).Distinct().OrderByDescending(x => x).Skip(2).FirstOrDefault();

Then you get null or (if exists) the third highest salary.然后你得到 null 或(如果存在)第三高的薪水。

var employees = Employees
    .GroupBy(e => e.Salary)
    .OrderByDescending(g => g.Key)
    .Skip(N-1)
    .First();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM