First clarify whether “second highest” means the second distinct salary or simply the second row after sorting. Interviewers usually mean the second distinct salary, so duplicate top salaries should count once. ```csharp decimal? secondHighest = employees .Select(employee => employee.Salary) .Distinct() .OrderByDescending(salary => salary) .Skip(1) .Cast<decimal?>() .FirstOrDefault(); ``` For EF Core, keep the query as `IQueryable` so filtering, distinct, ordering, and limiting are translated to SQL: ```csharp decimal? secondHighest = await db.Employees .Select(employee => employee.Salary) .Distinct() .OrderByDescending(salary => salary) .Skip(1) .Select(salary => (decimal?)salary) .FirstOrDefaultAsync(ct); ``` The nullable result represents fewer than two distinct salaries. To return every employee earning that amount, compute the value first and then issue a second filtered query, or use an appropriate window-function query where supported.
Krishna Yadav · · 0 likes