public class Solution {
    public int[] TopKFrequent(int[] nums, int k) {
        var freq = new Dictionary<int, int>();
        foreach (int x in nums)
            freq[x] = freq.GetValueOrDefault(x) + 1;
 
        var pq = new PriorityQueue<int, int>();
 
        foreach (var kvp in freq) {
            pq.Enqueue(kvp.Key, kvp.Value);
            if (pq.Count > k) pq.Dequeue();
        }
 
        return pq.UnorderedItems.Select(item => item.Element).ToArray();
    }
}

First we get the frequencies for all numbers in a dict.
Then we fill up the min heap for k largest (or frequent).
Finally return the items in the heap.