Find nth max salary using linq
I have a collection of Employee Data.
//7000,6000,5500,5000
List<Employee> employees = new List<Employee>()
{
new Employee { Id = 1, UserName = "Anil" , Salary = 5000},
new Employee { Id = 2, UserName = "Sunil" , Salary = 6000},
new Employee { Id = 3, UserName = "Lokesh" , Salary = 5500},
new Employee { Id = 4, UserName = "Vinay" , Salary = 7000},
new Employee { Id = 5, UserName = "Vijay" , Salary = 7000},
new Employee { Id = 6, UserName = "vikas" , Salary = 6000}
};
See the below query example. I am finding 2nd highest max Salary.
Query Example 1:
var result = employees.OrderByDescending(x => x.Salary)
.Select(x => x.Salary).Distinct().Take(3)
.Skip(3 - 1).FirstOrDefault();
Console.WriteLine(result);
Query Example 2:
var result = employees
.GroupBy(e => e.Salary)
.OrderByDescending(e=> e.Key)
.Skip(1)
.First();
Console.WriteLine(result.Key);
Query Example 3:
//This will return all employees who has 2nd highest salary
var result = employees
.Where(x1 => x1.Salary == employees.OrderByDescending(x => x.Salary)
.Select(x => x.Salary).Distinct().Take(2).Skip(2 - 1).FirstOrDefault())
.ToArray();
Console.WriteLine(result[0].Salary);
0 comments:
Post a Comment