wasAsked.

Write a LINQ query to find the 2 most expensive products.

PwC · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

Filter first, sort descending, then take two. Add a deterministic tie-breaker so repeated calls return stable results. Example: var top = await db.Products.AsNoTracking() .Where(p => p.IsActive) .OrderByDescending(p => p.Price) .ThenBy(p => p.Id) .Select(p => new { p.Id, p.Name, p.Price }) .Take(2) .ToListAsync(ct); For tenant-owned data, also filter with RestaurantId and OutletId from the authenticated context. An index beginning with those filters and including the ordering columns can help. Decide explicitly whether products tied at the second-highest price should all be returned; Take(2) returns exactly two rows.

Backbencher Developer · · 0 likes

Sort by price descending and take two. var topTwo = products .OrderByDescending(p => p.Price) .Take(2) .ToList(); Query syntax: var topTwo2 = (from p in products orderby p.Price descending select p).Take(2).ToList(); Make the result deterministic when prices tie: var topTwoStable = products .OrderByDescending(p => p.Price) .ThenBy(p => p.Name) .Take(2) .ToList(); Only names and prices: var topTwoNames = products .OrderByDescending(p => p.Price) .Take(2) .Select(p => new { p.Name, p.Price }) .ToList(); Two most expensive distinct prices (if "2 most expensive" means two price levels, including all products at those prices): var topPrices = products.Select(p => p.Price).Distinct().OrderByDescending(x => x).Take(2).ToList(); var productsAtTopPrices = products.Where(p => topPrices.Contains(p.Price)).ToList(); Most expensive product per category (a typical follow-up): var topPerCategory = products .GroupBy(p => p.CategoryId) .Select(g => g.OrderByDescending(p => p.Price).First()); With EF Core: var top = await db.Products.AsNoTracking() .OrderByDescending(p => p.Price) .Take(2) .ToListAsync(ct); // SELECT TOP(2) ... ORDER BY Price DESC Performance note OrderBy sorts the whole collection, O(n log n). For very large in-memory collections where you need only the top two, a single pass that tracks the best two items is O(n); .NET also has PriorityQueue<TElement, TPriority> for top-k problems. In the database, an index on Price makes the TOP query fast. For interviews, the LINQ version is the expected answer — then mention ties and performance to show depth.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics