Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the nth largest in an int array

Tags:

c#

linq

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
like image 599
Arnold Avatar asked Dec 30 '25 08:12

Arnold


1 Answers

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.

like image 162
har07 Avatar answered Dec 31 '25 22:12

har07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!