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 max Salary.
Query Example 1:
var employee = Employees.OrderByDescending(e => e.Salary).Skip(1).First();
var result = employees.OrderByDescending(x => x.Salary)
.Select(x => x.Salary).Distinct().Take(2)
.Skip(2 - 1).FirstOrDefault();
Console.WriteLine(result);
Query Example 2:
If multiple employees may have equal salary and you wish to return an IEnumerable of all the employees with the second-highest salary you could do:
var result = employees
.GroupBy(e => e.Salary)
.OrderByDescending(e=> e.Key)
.Skip(1)
.First();
Console.WriteLine(result.Key);
Find 2nd and 3rd max Number from below array using Linq
int[] numbers = { 1, 4, 2, 6, 3, 7, 9, 0 };
var secondMaxNumber = (from n in numbers orderby n descending select n)
.Take(2).LastOrDefault();
var thirdMaxNumber = (from n in numbers orderby n descending select n).Distinct()
.Skip(2).FirstOrDefault();
Console.WriteLine(secondMaxNumber); //7
Console.WriteLine(thirdMaxNumber); //6
0 comments:
Post a Comment