列表排序不正确

本文关键字:不正确 排序 列表 | 更新日期: 2023-09-27 18:35:31

我有以下代码

List<TimeZoneInfo> timeZoneList = new List<TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones());
timeZoneList.Sort((item1, item2) => { return string.Compare(item2.Id, item1.Id); });

但它没有正确排序列表。(使用 LINQ.OrderBy() 产生相同的结果)。
但以下代码排序正确。

List<string> timeZoneList1 = new List<string>();
foreach (TimeZoneInfo timeZoneInfo in TimeZoneInfo.GetSystemTimeZones())
            timeZoneList1.Add(timeZoneInfo.Id);
timeZoneList1.Sort((item1, item2) => { return string.Compare(item1, item2); });

问题出在哪里?我错过了什么?

真?
没有人知道答案?

---------------------------编辑------------------------------------
当我将列表分配给组合框时,它将以错误的顺序显示,但是当我设置组合框的显示成员时,它将得到修复。谁能解释这种行为?

列表排序不正确

您已在比较函数中交换了 item1 和 item2 的顺序。

在第一个示例中,您有以下行:

timeZoneList.Sort((item1, item2) => { return string.Compare(item2.Id, item1.Id); });

这不应该是:

timeZoneList.Sort((item1, item2) => { return string.Compare(item1.Id, item2.Id); });

在第一个示例中,string.Compare 方法中的项 ID 以错误的方式出现。在你的第二个例子中,它们是正确的方法,这就是为什么正确排序的原因。