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
If you are using .Net 6 and up you can use Comparer with PriorityQueue as:
For Increasing order:
PriorityQueue<int,int> pq = new PriorityQueue<int,int>(Comparer<int>.Create((a,b)=>a-b));
or for decreasing order:
PriorityQueue<int,int> pq = new PriorityQueue<int,int>(Comparer<int>.Create((a,b)=>b-a));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With