Results 1 to 3 of 3

Thread: Sorting strings numerically

  1. #1
    Member
    Join Date
    Oct 09
    Posts
    39

    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.

  2. #2
    Frenzied Member MattP's Avatar
    Join Date
    Dec 08
    Location
    WY
    Posts
    1,185

    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:
    1. Public Class Form1
    2.  
    3.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    4.         Dim itemList As New List(Of String) From {"item_1", "item_2", "item_4", "item_10", "item_8", "item_11"}
    5.         itemList.Sort(New NaturalComparerUsingAPI(False))
    6.     End Sub
    7.  
    8. End Class
    9.  
    10. Public Class NaturalComparerUsingAPI
    11.     Implements IComparer(Of String)
    12.  
    13.     Private Declare Unicode Function StrCmpLogicalW Lib "shlwapi.dll" (s1 As String, s2 As String) As Integer
    14.  
    15.     Private ReadOnly _order As Integer
    16.  
    17.     Public Sub New(Optional Ascending As Boolean = True)
    18.         _order = If(Ascending, 1, -1)
    19.     End Sub
    20.  
    21.     Public Function Compare(x As String, y As String) As Integer Implements IComparer(Of String).Compare
    22.         Return StrCmpLogicalW(x, y) * _order
    23.     End Function
    24.  
    25. 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.

  3. #3
    Member
    Join Date
    Oct 09
    Posts
    39

    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
  •