Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Lambda Comparator with PriorityQueue

Tags:

c#

.net

Documentation only shows deriving from IComparer and then specifying the derived class as the comparator in the constructor of PriorityQueue, but with multiple priority queues, it creates too many extra classes.

Is it possible to just use Lambda comparator with PriorityQueue class in C#?

like image 786
tunafish24 Avatar asked Jun 07 '26 09:06

tunafish24


1 Answers

While the other answer is good, the quick one-liner solution as mentioned in comments by other users is:

//Descending Sort, Integer
var queue = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y - x));

//Ascending Sort, Object
var queue = new PriorityQueue<ObjectA, ObjectB>(Comparer<ObjectB>.Create((x, y) => x.Something.CompareTo(y.Something));

Note that second element i.e. priority, can either be an object or primitive data type.

like image 169
tunafish24 Avatar answered Jun 09 '26 00:06

tunafish24



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!