wasAsked.

write a syntaxt for entity framework retrieve list of employee top 10 having higest salary, get fourth highest salary employee.

EY · Role not specified · technical

Published

Year not specified · Entity Framework Core

Community answers

Posted by wasAsked editorial collection

Top 10 employees with the highest salary: var top10 = await db.Employees .AsNoTracking() .OrderByDescending(e => e.Salary) .ThenBy(e => e.Id) // stable order when salaries tie .Take(10) .ToListAsync(ct); Generated SQL (SQL Server): SELECT TOP(10) ... FROM Employees ORDER BY Salary DESC, Id Projection version for an API: var top10Dto = await db.Employees .OrderByDescending(e => e.Salary) .Take(10) .Select(e => new { e.Id, e.Name, e.Salary }) .ToListAsync(ct); Employee(s) with the fourth highest salary "Fourth highest" usually means the fourth highest distinct salary value, so duplicates must not shift the position. decimal? fourthHighestSalary = await db.Employees .Select(e => (decimal?)e.Salary) .Distinct() .OrderByDescending(s => s) .Skip(3) .FirstOrDefaultAsync(ct); var fourth = fourthHighestSalary is null ? [] : await db.Employees.Where(e => e.Salary == fourthHighestSalary).ToListAsync(ct); If the interviewer means "the fourth row when sorted" (ignoring ties): var fourthRow = await db.Employees .OrderByDescending(e => e.Salary).ThenBy(e => e.Id) .Skip(3) .FirstOrDefaultAsync(ct); Query syntax alternative: var top10Query = await (from e in db.Employees orderby e.Salary descending select e).Take(10).ToListAsync(ct); Points to explain - Skip(n) and Take(n) translate to SQL OFFSET/FETCH (or TOP), so only the needed rows come from the database. - Casting to decimal? makes "no such salary" return null instead of 0. - Clarify whether ties count — distinct salary values versus row positions give different answers. - Add an index on Salary if this query runs frequently on large tables. - SQL equivalent with window functions: DENSE_RANK() OVER (ORDER BY Salary DESC) = 4. EF Core does not translate window functions directly in LINQ, but you can use FromSql for such queries if needed.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics