find the kth largest number in a list in csharp

One way to find the kth largest number in a list in C# is to sort the list in descending order using the built-in List.Sort() method or the LINQ OrderByDescending() method, and then access the element at the k-1th index.

Here's an example using the List.Sort() method:

main.cs
public static int KthLargest(List<int> numbers, int k)
{
    numbers.Sort(); // sorts in ascending order
    return numbers[numbers.Count - k]; // returns kth largest element
}
177 chars
6 lines

And here's an example using the LINQ OrderByDescending() method:

main.cs
public static int KthLargest(List<int> numbers, int k)
{
    return numbers.OrderByDescending(n => n).ElementAt(k-1); // sorts in descending order and returns kth largest element
}
181 chars
5 lines

Both methods have a time complexity of O(n log n) due to the sorting operation.

gistlibby LogSnag