List(Of IO.FileInfo)中带有前导数字的自然排序文件名?

时间:2014-08-15 14:29:23

标签: vb.net linq fileinfo natural-sort

我想对List(Of IO.FileInfo)

中的条目进行排序
1. Filename number One.txt
10. Filename number 10.txt
11. Filename number 11.txt
12. Filename number 12.txt
...
19. Filename number 19.txt
2. Filename number Two.txt
20. Filename number 20.txt
21. Filename number 21.txt
...

因为它们看起来很自然'按Windows文件浏览器中的前导数字排序:
 1./2。/ ... ... 10./11./12 19./20./21。

我使用以下代码填充List(Of IO.FileInfo)

Dim diStartDir As IO.DirectoryInfo = New IO.DirectoryInfo("C:\Temp")
Dim ListOfMatchingFiles As New List(Of IO.FileInfo)
For Each FileName In diStartDir.GetFiles("*.txt", IO.SearchOption.AllDirectories)
    ListOfMatchingFiles.Add(Filename)
Next

ListOfMatchingFiles.Sort() '<-- naturally sort is the tricky part...

在Visual Studio Designer中,我没有收到任何错误。如果我调试此代码,最后一个命令.Sort()会导致错误:

Fehler beim Vergleichen von zwei Elementen im Array.
An error occurred while comparing two elements.

我无法从 ICompare LINQ 中找到的示例中获得有效的解决方案。

你能用VB.NET代码帮助我吗,它可以自然地按(文件)名称对我的List(Of IO.FileInfo)进行排序吗?

1 个答案:

答案 0 :(得分:1)

我想,我找到了解决方案。如果要仅按文件名对List(Of IO.FileInfo)进行排序 - 没有完整路径 - 请添加以下Comparer类。
Comparer_FileInfo_Name_NaturalSort 重命名为您喜欢的任何内容:

Public Class Comparer_FileInfo_Name_NaturalSort
    Implements IComparer(Of IO.FileInfo)

    Declare Unicode Function StrCmpLogicalW Lib "shlwapi.dll" (ByVal s1 As String, ByVal s2 As String) As Integer

    Public Function Compare(fi1 As IO.FileInfo, fi2 As IO.FileInfo) As Integer Implements IComparer(Of IO.FileInfo).Compare
        Return StrCmpLogicalW(fi1.Name, fi2.Name)
    End Function
End Class



如果您希望按完整路径(包括文件名)排序,请将行替换为

    Return StrCmpLogicalW(fi1.FullName, fi2.FullName)



然后,您可以使用以下命令对List(Of IO.FileInfo)进行排序:

ListOfMatchingFiles.Sort(New Comparer_FileInfo_Name_NaturalSort)



我不确定,为什么很多例子都包含像

这样的行
<Security.SuppressUnmanagedCodeSecurity>

<Runtime.InteropServices.DllImport("shlwapi.dll", CharSet:=Runtime.InteropServices.CharSet.Unicode, ExactSpelling:=True)>

以及与上述声明Unicode函数

的确切区别