Search code examples
c#priority-queue

C# version of PriorityQueue for compare


I have the following code for Java and want to achieve same in C# . please suggest

    PriorityQueue<Integer> pQ= new PriorityQueue<Integer>((x,y)->Integer.compare(y, x));

I did convert Integer to int but does not helps.

.NET version < 6


Solution

  • If you are on .NET framework 6 (or newer) you just need:

    var pQ = new PriorityQueue<int, int>();
    

    If you add items you can give them a priority(2nd parameter):

    pQ.Enqueue(1, 100);
    pQ.Enqueue(2, 10);
    // ...
    

    or you have a complex logic that you want to reuse, then use a custom comparer:

    public class MyFancyIntComparer : IComparer<int>
    {
        public int Compare(int x, int y)
        {
            // replace following with a fancy logic
            return x.CompareTo(y);
        }
    }
    

    var pQ = new PriorityQueue<int, int>(new MyFancyIntComparer());
    

    If you are on a lower version of the .NET framework you might use(copy&paste) these internal PriorityQueues: https://referencesource.microsoft.com/#q=priorityqueue