如何以与文件资源管理器名称倒序相同的反向字母数字顺序对目录文件路径列表进行排序(当单击“名称”两次时)?
当“#”后面的位数不同时,Array.Sort 方法无法正确对文件名进行排序。
例如,当视图按名称顺序排列时,文件名“Osopcoz #777 1.TXT”正确地是文件资源管理器中显示的目录中的第三个文件:
这是具有正确顺序的文件资源管理器......
但 Array.Sort 将此文件名放在所有文件名的末尾,其中 # 后面有两位数字
HERE IS Array.Sort with incorrect order...
你可以使用原生的StrCmpLogicalW()功能创建您自己的字符串比较器。它使用一种称为自然排序,这与 Explorer 使用的算法相同(很可能 Explorer 也使用这个确切的方法)。
要使其按降序排序,您只需对返回值取反即可StrCmpLogicalW()
.
<SuppressUnmanagedCodeSecurity()> _
Public Class NaturalSortComparer
Implements IComparer(Of String)
<DllImport("shlwapi.dll", CharSet:=CharSet.Unicode)> _
Private Shared Function StrCmpLogicalW(ByVal psz1 As String, ByVal psz2 As String) As Integer
End Function
Public Property SortDescending As Boolean = False
Public Sub New()
End Sub
Public Sub New(ByVal SortDescending As Boolean)
Me.SortDescending = SortDescending
End Sub
Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements IComparer(Of String).Compare
Dim Result As Integer = StrCmpLogicalW(x, y)
Return If(Me.SortDescending, -Result, Result)
End Function
End Class
Usage:
Array.Sort(myArray, New NaturalSortComparer(True)) 'True specifies descending sort order.
在线测试: https://dotnetfiddle.net/MfLaZx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)