Saturday, 21 January 2023

LINQ query related questions

 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

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives