|
-
Jul 19th, 2012, 04:48 PM
#1
Thread Starter
Member
Sorting strings numerically
When I am reading a folder of filenames into an array with My.Computer.FileSystem.GetFiles and writing this array sequentially in a listbox/checkedlistbox the file names are showing up in the format:
Code:
Name.1
Name.10
Name.2
Name.3
Name.4
Name.5
Name.6
Name.7
Name.8
Name.9
I do not have control over the filenames so I can’t change the format to add leading zeros or anything, and I obviously can’t modify them in the program because then they wouldn’t point to their respective files anymore. I am trying to get VB to sort like Windows default sorting, which lists them in numerical order. I remember having had this problem and solving it once before a while ago (I don't think it was that hard), but can’t remember how I did it.
-
Jul 19th, 2012, 05:03 PM
#2
Re: Sorting strings numerically
Here's a comparer I wrote awhile back to implement natural sorting like Windows uses.
If you'd rather use the shell api to do it you can implement it like this:
vb.net Code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim itemList As New List(Of String) From {"item_1", "item_2", "item_4", "item_10", "item_8", "item_11"}
itemList.Sort(New NaturalComparerUsingAPI(False))
End Sub
End Class
Public Class NaturalComparerUsingAPI
Implements IComparer(Of String)
Private Declare Unicode Function StrCmpLogicalW Lib "shlwapi.dll" (s1 As String, s2 As String) As Integer
Private ReadOnly _order As Integer
Public Sub New(Optional Ascending As Boolean = True)
_order = If(Ascending, 1, -1)
End Sub
Public Function Compare(x As String, y As String) As Integer Implements IComparer(Of String).Compare
Return StrCmpLogicalW(x, y) * _order
End Function
End Class
Last edited by MattP; Jul 19th, 2012 at 05:11 PM.
This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.
The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.
-
Jul 20th, 2012, 09:09 AM
#3
Thread Starter
Member
Re: Sorting strings numerically
Thanks! I used the method from your linked post, it worked beautifully!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|