Second Highest Distinct Salary with LINQ
csharpC# and .NETinterview-prepintermediate
The classic Nth-highest question in LINQ: take the distinct values, sort them descending, skip one, and handle the case where there is no second value.
int[] salaries = { 90000, 75000, 75000, 60000 };
Console.WriteLine(NthHighest(salaries, 2)?.ToString() ?? "none"); // 75000
Console.WriteLine(NthHighest(salaries, 5)?.ToString() ?? "none"); // none
Console.WriteLine(NthHighest(new[] { 50000 }, 2)?.ToString() ?? "none"); // none
// Distinct first, so people sharing the top salary do not count as different ranks.
// Returns null when there are fewer than n distinct values.
static int? NthHighest(IEnumerable<int> values, int n) =>
values.Distinct()
.OrderByDescending(v => v)
.Skip(n - 1)
.Select(v => (int?)v)
.FirstOrDefault();