In this post, I will explain a LINQ Query to find nth Lowest Salary.
In below LINQ query, the subquery returns the count of a distinct salary lower than current employee salary. Then the result of subquery will be compared with N and record with subquery result count equal N will be returned as result.
int N = 2;
var employees = DB.Employees
.Where(em1 =>
db.Employees.Select(em2 => new { em2.Salary })
.Where(em2 => em2.Salary < em1.Salary)
.Distinct().Count().Equals(N)
);
GridView1.DataSource = employees;
GridView1.DataBind();
Table Script-
CREATE TABLE Employee(
EmployeeId int IDENTITY(1,1) ,
EmployeeName varchar(100) NULL,
Salary decimal(18, 2) NULL,
)
In below LINQ query, the subquery returns the count of a distinct salary lower than current employee salary. Then the result of subquery will be compared with N and record with subquery result count equal N will be returned as result.
int N = 2;
var employees = DB.Employees
.Where(em1 =>
db.Employees.Select(em2 => new { em2.Salary })
.Where(em2 => em2.Salary < em1.Salary)
.Distinct().Count().Equals(N)
);
GridView1.DataSource = employees;
GridView1.DataBind();
Table Script-
CREATE TABLE Employee(
EmployeeId int IDENTITY(1,1) ,
EmployeeName varchar(100) NULL,
Salary decimal(18, 2) NULL,
)