What should IComparer return to indicate "keep the existing sort order",

I am implementing a custom comparer to apply a custom sort order for elements in different views.

For a while I find that I want to keep the existing order of the elements, in this case, what should I return from my implementation of the Compare method? Is it enough to simply return 0, or do I really need to determine which element was the first?

+8
c # icomparer
source share
2 answers

(Credit for this answer goes to Lee )

It depends on whether the algorithm used for sorting is stable . For example, OrderBy is stable and therefore returning 0 from Compare will mean that the two elements will retain their original order in the list, however, List.Sort will not, and therefore returning 0 from Compare does not guarantee that the two elements will be in the original order in sorted form.

+2
source share

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

+1
source share

All Articles