Search code examples
c#lambdapriority-queueicomparer

Getting error Cannot convert Generic.Comparer<Pair> to Generic.IComparer<int> while comparing two objects in a priority queue in c# using lambda ex


I have a pair class.

public class Pair
{
    public int freq;
    public int coolTime;
    
    public Pair(int freq, int coolTime)
    {
        this.freq = freq;
        this.coolTime = coolTime;
    }
}

I want to create a priority queue with a custom comparer to make it a maxheap. I am trying to do it using lambda. I am not understanding where is the problem. Here are the things that I have tried.

 var pq = new PriorityQueue<Pair, int>(Comparer<Pair>.Create((x, y) => y.freq.CompareTo(x.freq)));

I know I am making some silly mistake but I am not sure what it is. Any help will be appreciated.

Edit: This is th error I am getting at compile time. enter image description here


Solution

  • The comparer for PriorityQueue<TElement, TPriority> compares the priority, not the element. This is what the error message is telling you.

    Change your code to compare the priority like this:

    var pq = new PriorityQueue<Pair, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
    

    Priority Queue Docs