I need to be able to find the nth largest numbers in an int array, I already have a linq statement that returns something but it's not passing the used cases that are set up. The array is:
var numbers = new[] { 5, 7, 5, 3, 6, 7, 9 };
My code is:
var result = numbers.GroupBy(x => x)
.OrderByDescending(group => group.Key)
.SkipWhile(group =>
{
n -= group.Count();
return n > 0;
})
.First()
.ToArray();
I don't understand why I'm not getting the expected results?
result[0] == 9
result[1] == 7
You can just use Take() to get the n largest items after the collection is ordered descending :
var result = numbers.GroupBy(x => x)
.OrderByDescending(group => group.Key)
.Take(n)
.Select(group => group.Key)
.ToArray();
dotnetfiddle demo
or use Skip(n-1).Take(1) if you mean to get only the nth item instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With