I'm trying to create a priority queue in C# that consists of 64-bit (long) integers in DESCENDING order. Unfortunately, it looks like .NET doesn't support this?
Here's the code that fails:
PriorityQueue<long, long> pq = new PriorityQueue<long, long>(Comparer<long>.Create((x, y) => y - x));
And here are the errors it generates:
error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
It should be noted that everything works perfectly if I change all the "long" references to "int".
Is there a cast I can put somewhere to make this work or is this just a basic feature that C# doesn't support for whatever reason?
Not sure what you were trying to do with y - x
, that would give you incorrect results in some cases.
It was erroring because you were returning a long
, and Compare
expects an int
which is:
0
for equal valuesThe simplest way to return the reverse comparison is to just flip the operands. Compare x against y rather than the other way round.
var comparer = Comparer<long>.Create((x, y) => y.CompareTo(x));
PriorityQueue<long, long> pq = new PriorityQueue<long, long>(comparer);