此函数使用冒泡算法IO.DirectoryInfo
按Name
属性对列表进行排序。
如何在参数中指定要对列表进行排序的属性?
例如:“Drive”、“Name”、“Name.Length”、“Directory.Parent”等...
我认为一个好主意(也许不好,我不知道可以改进多少)是将参数作为字符串传递,然后将字符串转换为...?这是我迷路的地方。
Public Shared Function BubbleSort_List(list As List(Of IO.DirectoryInfo), ByVal SortByProperty As ...) As List(Of IO.DirectoryInfo)
Return list.Select(Function(s) New With { _
Key .OrgStr = s, _
Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
s.Name, "(\d+)|(\D+)", _
Function(m) m.Value.PadLeft(list.Select(Function(folder) folder.Name.Length).Max, _
If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
}).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
End Function
更新:
请注意上面代码的这一部分:
list.Select(Function(folder) folder.Name.Length).Max
我需要的是调用指定我想要的属性而不是“名称”属性的函数。
更新 2
尝试使用@Sriram Sakthivel 解决方案,但它在 [property] 变量中引发关于 UnaryExpression 到 MemberExpression 之间不兼容转换的异常。
Imports System.Reflection
Imports System.Linq.Expressions
Private Sub Test(sender As Object, e As EventArgs) Handles MyBase.Shown
' Here I create the list
Dim Folders As List(Of IO.DirectoryInfo) = _
IO.Directory.GetDirectories("E:\Música\Canciones", "*", IO.SearchOption.TopDirectoryOnly) _
.Select(Function(p) New IO.DirectoryInfo(p)).ToList()
' Here I try to loop the list at the same time I try to sort it,
' specifying the property I want using @Sriram Sakthivel solution,
' This part does not work because the second parametter is wrong.
For Each folderinfo In BubbleSort_List(Folders, Function() Name)
MsgBox(folderinfo.Name)
Next
End Sub
Private Function BubbleSort_List(list As List(Of IO.DirectoryInfo), exp As Expression(Of Func(Of Object))) As List(Of IO.DirectoryInfo)
Dim [property] As PropertyInfo = DirectCast(DirectCast(exp.Body, MemberExpression).Member, PropertyInfo)
Return list.Select(Function(s) New With { _
Key .OrgStr = s, _
Key .SortStr = System.Text.RegularExpressions.Regex.Replace( _
s.Name, "(\d+)|(\D+)", _
Function(m) m.Value.PadLeft(list.Select(Function(folder) DirectCast([property].GetValue(folder, Nothing), String).Length).Max(), _
If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
}).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
End Function