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

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?

Upvotes: 4

Views: 1856

Answers (5)

xhafan
xhafan

Reputation: 2416

StableSort() extension method for List<T> is here

Upvotes: 2

digEmAll
digEmAll

Reputation: 57220

Sort uses QuickSort, and it doesn't assure original sequence in case of comparison equality.

If you still want to use List.Sort you could add a second comparison with the original index like:

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 (e.g. LINQ OrderBy).

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129802

OrderBy preserves order for equal items:

myList = myList.OrderBy(item => item.SortIndex).ToList();

Upvotes: 5

Oded
Oded

Reputation: 499172

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

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

Upvotes: 1

Mark Heath
Mark Heath

Reputation: 49512

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

Upvotes: 5

Related Questions