为什么 C# 中的 List.Sort 方法会颠倒列表的顺序?
我有一个通用列表中的项目列表:
- A1 (排序索引 1)
- A2 (排序索引 2)
- B1 (排序索引 3)
- B2 (排序索引 3)
- B3 (排序索引 3)
形式:
this.sortIndex.CompareTo(other.sortIndex)
它们的比较器采用以下 我在项目列表上执行 List.Sort() ,得到以下顺序:
- A1
- A2
- B3
- B2
- B1
从排序索引顺序正确的意义上来说,它显然有效,但我真的不想要它要重新订购“B”项目。
我可以对比较器进行任何调整来解决这个问题吗?
I have a list of items in a generic list:
- A1 (sort index 1)
- A2 (sort index 2)
- B1 (sort index 3)
- B2 (sort index 3)
- B3 (sort index 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:
- A1
- A2
- B3
- B2
- 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.
Is there any tweak I can make to my comparator to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
OrderBy
保留相同项目的顺序:OrderBy
preserves order for equal items:如果您不想要以下项目,则需要使用“稳定排序”算法等于改变位置。
查看“合并排序”以获得稳定排序算法的示例。下面是它在 C# 中的实现。
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#.
List
的StableSort()
扩展方法位于此处StableSort()
extension method forList<T>
is here您可以更改比较器以对值进行二次排序:
You can change your comparator to do a secondary sort on the value:
排序使用QuickSort,在比较相等的情况下不保证原始顺序。
如果您仍然想使用 List.Sort,您可以添加与原始索引的第二个比较,例如:
否则您可以使用其他“稳定”算法(例如 LINQ OrderBy)进行排序。
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:
otherwise you can sort with other "stable" algorithms (e.g. LINQ OrderBy).