您可以使用数据绑定而不是将项目一一添加到ListBox
. 我建议您先将文件添加到列表中,然后对列表进行排序并将其分配给ListBox
.DataSource
定义一个类成员的列表
Private _list As New List(Of String)()
将其分配给ListBox
listBox1.DataSource = _list
然后添加新的列表条目
_list.Add("new file")
_list.Sort()
' Refresh the ListBox
listBox1.DataSource = Nothing
listBox1.DataSource = _list
更新
如果你想实现自己的排序顺序,那么实现一个IComparer(Of String)
Class MyFileComparer
Implements IComparer(Of String)
Public Function Compare(x As String, y As String) As Integer _
Implements IComparer(Of String).Compare
Const AlwaysFirst As String = "FILE1"
Dim x = If(x.Contains(AlwaysFirst), "1_", "2_") & x
Dim y = If(y.Contains(AlwaysFirst), "1_", "2_") & y
' Note: If "FILE1" appears always at the end then this would be better
'Dim x = If(x.EndsWith(AlwaysFirst & ".txt"), "1_", "2_") & x
'Dim y = If(y.EndsWith(AlwaysFirst & ".txt"), "1_", "2_") & y
' Normalize strings (e.g. if "File_123.txt" = ""File 123.txt")
x = x.Replace("_"C, " "C)
y = y.Replace("_"C, " "C)
Return x.CompareTo(y)
End Function
End Class
然后你可以像这样排序
Static comparer = New MyFileComparer()
_list.Sort(comparer)
更新#2
我不知道你的文件是如何准确命名的,但是如果它们总是以你结尾,"FILE<number>.<ext>"
你也可以像这样更改字符串比较的文件名:
原始文件名
abc_FILE1.txt
abc_123_FILE2.txt
sssd_FILE23.txt
xxx_24_FILE073.txt
准备好的文件名
FILE001_abc.txt
FILE002_abc_123.txt
FILE023_sssd.txt
FILE073_xxx_24.txt
现在该Compare
方法可以简单地确定结果
Return x_prepared.CompareTo(y_prepared)