I have a list of items in a generic list:
The comparator on them takes the form:
this.sortIndex.CompareTo(other.sortIndex)
When I do a List.Sort() on the list of items, I get the following order out:
It has obviously worked in the sense that the sort indexes are in the right order, but I really don't want it to be re-ordering the 'B' items.
Is there any tweak I can make to my comparator to fix this?
OrderBy
preserves order for equal items:
myList = myList.OrderBy(item => item.SortIndex).ToList();
you need to use a "stable sort" algorithm if you don't want items that are equal to change position.
Check out "merge sort" for an example of a stable sort algorithm. Here's an implementation of it in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With