What should IComparer return to indicate "keep the existing sort order"
Asked Answered
C

2

10

I'm implementing a custom comparer in order to apply a custom sort order for items in various views.

Some of the time I'm finding that I want to maintain the existing order of items, in this case what should I return from my Compare method implementation? Is it enough to simply return 0, or do I actively need to identify which item came first?

Carcanet answered 8/4, 2013 at 15:28 Comment(7)
I'm pretty sure returning 0 will leave adjacent items as-isQuixotism
@Quixotism Thats what I think, however according to the documentation that technically means x equals y, which in theory means that the sorter can put those two items in whatever order it choosesCarcanet
It depends on what you use to do the ordering, Enumerable.OrderBy does a stable sort, List<T>.Sort is not stable, so it could re-order equal elements.Amusing
@Amusing Fantastic, just found stability in wikipedia, plus notes in the OrderBy and Sort documentation explaining that they are stable and not stable respectively - that answers my question perfectlyCarcanet
@Justin, rather than relying on other interested users reading the comments, it would be worth adding a quick answer to your own question so people know there's something useful here. Interesting question, too!Fey
@Fey I was waiting to see if Lee converted his comment into an answer firstCarcanet
@Carcanet fair enough, just thought I'd point it out in case it turned into a fire-and-forget question :)Fey
C
4

(Credit for this answer goes to Lee)

It depends on whether or not the algorithm used to do the sorting is stable. For example, the OrderBy is stable and so returning 0 from Compare will mean that the two items retain their original order in the list, however List.Sort is not, and so returning 0 from Compare doesn't guarentee that the two items will be in their original order in the sorted output.

Carcanet answered 10/4, 2013 at 14:10 Comment(0)
A
1

Zero, but your sort algorithm may still change its order.

Apsis answered 10/4, 2013 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.