Sorting an array of folder names like Windows Explorer (Numerically and Alphabetically) - VB.NET

前端 未结 2 1305
我寻月下人不归
我寻月下人不归 2020-11-28 12:04

I\'m killing myself and dehydrating trying to get this array to sort.

I have an array containing directories generated by;

Dim Folders() As String = Director

相关标签:
2条回答
  • 2020-11-28 12:43

    You would need to implement an IComparer, as opposed to creating a class that implements IComparable. The difference is that an IComparer has the necessary "knowledge" to compare two objects whereas IComparable is implemented by a class that knows how to compare itself against something else.

    And the way Windows Explorer sorts filenames is using a function called StrCmpLogicalW. You can use this function in your own IComparer to get the same sort behavior as Windows Explorer. This function treats numeric parts of strings as numbers so that 9 sorts before 10.

    public class MyComparer : IComparer<string> {
    
        [DllImport("shlwapi.dll", CharSet=CharSet.Unicode, ExactSpelling=true)]
        static extern int StrCmpLogicalW(String x, String y);
    
        public int Compare(string x, string y) {
            return StrCmpLogicalW(x, y);
        }
    
    }
    
    Array.Sort(unsortedNames, new MyComparer());
    

    And since I just noticed the question is tagged VB... Forgive my rusty VB!

    Public Class MyComparer
        Implements IComparer(Of String)
    
        Declare Unicode Function StrCmpLogicalW Lib "shlwapi.dll" ( _
            ByVal s1 As String, _
            ByVal s2 As String) As Int32
    
        Public Function Compare(Byval x as String, Byval y as String) As Integer _
            Implements System.Collections.Generic.IComparer(Of String).Compare
    
            Return StrCmpLogicalW(x, y)
    
        End Function
    
    End Class
    
    0 讨论(0)
  • 2020-11-28 12:53

    Array.Sort has an IComparer parameter too, you can override sorting behavior if you don't like the default. see Array.Sort Method (T[], IComparer) how to do it

    0 讨论(0)
提交回复
热议问题