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

发布于 2024-08-29 16:41:56 字数 432 浏览 8 评论 0原文

我有一个通用列表中的项目列表:

  • 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一瞬间的火花 2024-09-05 16:41:56

OrderBy 保留相同项目的顺序:

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

OrderBy preserves order for equal items:

myList = myList.OrderBy(item => item.SortIndex).ToList();
指尖凝香 2024-09-05 16:41:56

如果您不想要以下项目,则需要使用“稳定排序”算法等于改变位置。

查看“合并排序”以获得稳定排序算法的示例。下面是它在 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#.

梦境 2024-09-05 16:41:56

ListStableSort() 扩展方法位于此处

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

鲜血染红嫁衣 2024-09-05 16:41:56

您可以更改比较器以对值进行二次排序:

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

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;
聚集的泪 2024-09-05 16:41:56

排序使用QuickSort,在比较相等的情况下不保证原始顺序。

如果您仍然想使用 List.Sort,您可以添加与原始索引的第二个比较,例如:

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

否则您可以使用其他“稳定”算法(例如 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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文