3

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
Hexie
  • 3,955
  • 6
  • 32
  • 55
Arnold
  • 69
  • 1
  • 11

1 Answers1

3

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.

har07
  • 88,338
  • 12
  • 84
  • 137