When sorting the file name in C#, it is usually necessary to use natural sorting algorithms instead of default dictionary sorting. This can ensure that the number is sorted in numerical, and the number of letters is sorted in appropriate order.
One way to achieve natural sorting is to use the built -in Windows function
. This function allows to compare the logical order of the string (including the number of numbers as a value) and the sorted string.
StrCmpLogicalW
StrCmpLogicalW
You can use to access Function:
DllImport
Use iComparer's implementation StrCmpLogicalW
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2);
array sort, you can implement a custom class, as shown below:
<示> Example usage FileInfo
IComparer
public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return StrCmpLogicalW(x.Name, y.Name); } }
This will sort the
arrays according to the natural order of the file name (at the same time considering the number and letter sequence of the letter).The above is the detailed content of How Can I Implement Natural Sort Order for File Names in C#?. For more information, please follow other related articles on the PHP Chinese website!