简体   繁体   English

为什么我在C#中的List.Sort方法颠倒了我的列表顺序?

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

I have a list of items in a generic list: 我有一个通用列表中的项目列表:

  • A1 (sort index 1) A1(排序索引1)
  • A2 (sort index 2) A2(排序索引2)
  • B1 (sort index 3) B1(排序索引3)
  • B2 (sort index 3) B2(排序索引3)
  • B3 (sort index 3) B3(排序索引3)

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: 当我在项目列表上执行List.Sort()时,我得到以下顺序:

  • A1 A1
  • A2 A2
  • B3 B3
  • B2 B2
  • B1 B1

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. 它显然起作用,排序索引的顺序是正确的,但我真的不希望它重新排序'B'项。

Is there any tweak I can make to my comparator to fix this? 我可以对比较器进行调整以解决这个问题吗?

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#. 这是C#中的一个实现

OrderBy保留相同项目的订单:

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

List<T> StableSort()扩展方法在这里

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;

Sort uses QuickSort, and it doesn't assure original sequence in case of comparison equality. Sort使用QuickSort,并且在比较相等的情况下不保证原始序列。

If you still want to use List.Sort you could add a second comparison with the original index like: 如果您仍想使用List.Sort,您可以添加与原始索引的第二个比较,如:

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 (eg LINQ OrderBy). 否则你可以使用其他“稳定”算法(例如LINQ OrderBy)进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM