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

StackOverflow https://stackoverflow.com/questions/15883112

  •  02-04-2022
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

(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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top