See Int32.CompareTo for the sorting method that this lambda expression is replacing. Normally, we'd have:
x < y
: return -1x == y
: return 0x > y
: return 1
Instead, we have:
- x odd, y even: return -1
- x odd, y odd OR x even, y even: return 0
- x even, y odd: return 1
Since the elements in the sets {1, 3, 5}
are equal and {2, 4}
are equal, you're at the mercy of the sorting algorithm used for the exact order of the final set. The sorted list will have the form {odds, evens}
, but the orders of those sublists will depend on the algorithm. Per MSDN, Array.Sort uses Insertion sort if the array has fewer than 16 elements.
When I do this, the order I get back is {1, 3, 5, 2, 4}
, which is what I would expect, not {3, 5, 1, 2, 4}
UPDATE:
It was pointed out in the comments that x % 2 == -1
for negative odd integers, which means that the above needs some reworking for the general int
. (I apologize, but my math background means I think of mod as an unsigned value.)
- x odd, y even OR (x odd, y odd, x > 0 > y): return -1
- (x odd, y odd, same sign) OR x even, y even: return 0
- x even, y odd OR (x odd, y odd, x < 0 < y) : return 1
This will mean that we end up with a list of the form {positive odds, negative odds, evens}
.