Natural Sort Order in C#

后端 未结 17 2085
野性不改
野性不改 2020-11-21 04:54

Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo array? I am implementing the IComparer interface in

17条回答
  •  野性不改
    2020-11-21 05:54

    Let me explain my problem and how i was able to solve it.

    Problem:- Sort files based on FileName from FileInfo objects which are retrieved from a Directory.

    Solution:- I selected the file names from FileInfo and trimed the ".png" part of the file name. Now, just do List.Sort(), which sorts the filenames in Natural sorting order. Based on my testing i found that having .png messes up sorting order. Have a look at the below code

    var imageNameList = new DirectoryInfo(@"C:\Temp\Images").GetFiles("*.png").Select(x =>x.Name.Substring(0, x.Name.Length - 4)).ToList();
    imageNameList.Sort();
    

提交回复
热议问题