Why is my List.Sort method in C # overriding the order of my list?

I have a list of items in a general list:

  • A1 (sort index 1)
  • A2 (sorting index 2)
  • B1 (sorting index 3)
  • B2 (sorting index 3)
  • B3 (sort index 3)

The comparator on them takes the form:

this.sortIndex.CompareTo(other.sortIndex) 

When I do List.Sort () on a list of items, I get the following order:

  • A1
  • A2
  • B3
  • IN 2
  • B1

Obviously, it worked in the sense that the sort indices are in the correct order, but I really don't want it to reorder the "B" elements.

Are there any settings I can make for my comparator to fix this?

+4
source share
5 answers

OrderBy keeps order for equal elements:

 myList = myList.OrderBy(item => item.SortIndex).ToList(); 
+5
source

you need to use the stable sort algorithm if you do not want positions that are equal to the change position,

Check merge sort "for an example of a stable sorting algorithm. Here's the implementation in C #.

+5
source

StableSort() extension method for List<T> here

+2
source

You can change your comparator to do a secondary sort by value:

 if (this.sortIndex.CompareTo(other.sortIndex) == 0) // same sortIndex { return this.Value.CompareTo(other.Value); } return 0; 
+1
source

Sorting uses QuickSort and does not guarantee the original sequence in case of equality of comparisons.

If you still want to use List.Sort, you can add a second comparison with the original index, for example:

 int c = this.sortIndex.CompareTo(other.sortIndex); if (c == 0) c = this.originalIndex.CompareTo(other.originalIndex); return c; 

otherwise, you can sort with other "stable" algorithms (for example, LINQ OrderBy).

+1
source

Source: https://habr.com/ru/post/1307439/


All Articles