列表排序未产生预期结果

时间:2019-03-12 03:09:05

标签: c#

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

    // 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

我误会排序了吗?

1 个答案:

答案 0 :(得分:3)

内部字符串比较器compares string by words,因此请使用肯定的比较器,例如:

FileList.Sort(string.CompareOrdinal);