我有一个通用列表中的项目列表:
- A1(排序索引 1)
- A2(排序索引 2)
- B1(排序索引 3)
- B2(排序索引 3)
- B3(排序索引 3)
它们上的比较器采用以下形式:
this.sortIndex.CompareTo(other.sortIndex)
当我对项目列表执行 List.Sort() 时,我得到以下顺序:
- A1
- A2
- B3
- B2
- B1
它显然在排序索引的顺序正确的意义上起作用,但我真的不希望它重新排序“B”项。
我可以对比较器进行任何调整来解决这个问题吗?
我有一个通用列表中的项目列表:
它们上的比较器采用以下形式:
this.sortIndex.CompareTo(other.sortIndex)
当我对项目列表执行 List.Sort() 时,我得到以下顺序:
它显然在排序索引的顺序正确的意义上起作用,但我真的不希望它重新排序“B”项。
我可以对比较器进行任何调整来解决这个问题吗?
OrderBy
保留相同项目的顺序:
myList = myList.OrderBy(item => item.SortIndex).ToList();
StableSort()
扩展方法List<T>
在这里
您可以更改比较器以对值进行二次排序:
if (this.sortIndex.CompareTo(other.sortIndex) == 0) // same sortIndex
{
return this.Value.CompareTo(other.Value);
}
return 0;
排序使用快速排序,在比较相等的情况下不保证原始顺序。
如果您仍想使用 List.Sort,您可以添加与原始索引的第二个比较,例如:
int c = this.sortIndex.CompareTo(other.sortIndex);
if (c == 0)
c = this.originalIndex.CompareTo(other.originalIndex);
return c;
否则,您可以使用其他“稳定”算法(例如 LINQ OrderBy)进行排序。