This function uses the bubble algorithm to sort a list of IO.DirectoryInfo
by their Name
property.
How I can specify in a parameter the property that I will to sort the list?
For example: "Drive", "Name", "Name.Length", "Directory.Parent", etc...
What I thought like a good idea (maybe is not good, I don't know how much can be improved this) is to pass the parameter as string and then cast the string as...? Here is where I'm lost.
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
UPDATE:
Notice this part of the code above:
list.Select(Function(folder) folder.Name.Length).Max
What I need is to call the function specifying the property that I want instead "Name" property.
UPDATE 2
Trying to use the @Sriram Sakthivel solution but it throws an exception at the [property] variable about incompatible casting between UnaryExpression to 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