Sorting Items In A Listbox Numerically

993 views Asked by At

I'm having trouble sorting items in a listbox numerically. All my filenames that have a "1" are grouped together. Example = (file1, file10, file11, file2, file3, file4, etc)

I have the Sorted option on the listbox set to True but doesn't appear to work correctly.

Here's how I'm currently adding my items.

    Dim directoryInfo As New System.IO.DirectoryInfo(TextBox1_Path.Text)
    Dim fileInfos() As System.IO.FileInfo            
    fileInfos = directoryInfo.GetFiles()
    For Each fileInfo As System.IO.FileInfo In fileInfos
        ListBoxUPSFiles.Items.Add(fileInfo.Name)
    Next

I'd like to sort them as file1, file2, file3, file4, etc.

Suggestions on sorting the filenames?

1

There are 1 answers

1
Magnus On BEST ANSWER

Remove the listbox sorting and do:

For Each fileInfo As System.IO.FileInfo In fileInfos.OrderBy( _
    Function(fi) Integer.Parse(Regex.Match(fi.Name, "\d+").Value))
    ListBoxUPSFiles.Items.Add(fileInfo.Name)
Next