首页 > 解决方案 > 列表排序未产生预期结果

问题描述

我有一个似乎没有正确排序的列表。为了找出发生了什么,我添加了代码:

    // save unsorted list
    using (StreamWriter listfile = new StreamWriter("D:\\UnsortedList.csv", 
    false))
    {
        foreach (string currentLine in FileList)
        {
            listfile.WriteLine(currentLine);
        }
        listfile.Close();
    }

然后我对其进行排序并将结果保存到另一个文件:-

FileList.Sort();
// save sorted list
using (StreamWriter listfile = new 
StreamWriter("D:\\UnfilteredFileList.csv", false))
{
    foreach (string currentLine in FileList)
    {
        listfile.WriteLine(currentLine);
    }
listfile.Close();
}

第一个未排序的文件包含一些行(我添加的行号):

1   attributes\53.p_40NB MED 90º ELBOW,zipped
2   attributes\6.00 B02 level.PObjGrp,zipped
3   attributes\6.00- B02 level.PObjGrp,zipped
4   attributes\6.01- B02 level.PObjGrp,zipped
5   attributes\6.02- B03 level.PObjGrp,zipped
..........
6   attributes\53.p_40NB MED 90º ELBOW,folder
7   attributes\6.00 B02 level.PObjGrp,folder
8   attributes\6.00- B02 level.PObjGrp,folder
9   attributes\6.01- B02 level.PObjGrp,folder
10  attributes\6.02- B03 level.PObjGrp,folder

在排序之后,我预计第 7 行将在第 2 行之前结束。相反,我得到了:

attributes\53.p_40NB MED 90º ELBOW,zipped
attributes\6.00 B02 level.PObjGrp,folder
attributes\6.00- B02 level.PObjGrp,folder
attributes\6.00 B02 level.PObjGrp,zipped
attributes\6.00- B02 level.PObjGrp,zipped
attributes\6.01- B02 level.PObjGrp,folder

我误解了排序吗?

标签: c#

解决方案


内部字符串比较器逐字比较字符串,所以使用肯定比较器,如:

FileList.Sort(string.CompareOrdinal);

推荐阅读