LINQ Interview Question #138
How can LINQ find the second-highest value?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
The correct query depends on whether duplicate values count as separate positions. For the second-highest distinct value, project the value, remove duplicates, order descending, skip the highest, and take the next.
Detailed Explanation
The correct query depends on whether duplicate values count as separate positions. For the second-highest distinct value, project the value, remove duplicates, order descending, skip the highest, and take the next.
If fewer than two distinct values exist, FirstOrDefault may return the type's default, so nullable projection or explicit validation can be preferable.
Code Example
decimal? secondHighest = products
.Select(p => (decimal?)p.Price)
.Distinct()
.OrderByDescending(p => p)
.Skip(1)
.FirstOrDefault();