我正在编写一个简单的应用程序来从目录中收集名为date的文件夹并添加到combobox。我想在添加之前对列表进行排序? 任何建议
Dim filepath As String = FileStr
Dim directoryPath As String = System.IO.Path.GetDirectoryName(filepath)
For Each file As String In System.IO.Directory.GetFiles(directoryPath)
ComboBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
答案 0 :(得分:0)
您可以使用LINQ的OrderBy
和Date.TryParseExact
。我也会使用Directory.EnumerateFiles
,因为它不需要读取所有文件。
Dim formats = {"dd-MM-yyyy", "yyyyMMdd"}
Dim dt As DateTime
Dim orderedFiles = From file In System.IO.Directory.EnumerateFiles(directoryPath)
Let fileName = System.IO.Path.GetFileNameWithoutExtension(file)
Where Date.TryParseExact(fileName, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, dt)
Order By dt Ascending
Select fileName
For Each fileName As String In orderedFiles
ComboBox1.Items.Add( fileName )
Next