在另一个问题(这里:Pass an IO.DirectoryInfo property as a parameter to a function?)我询问如何改进函数以将DirectoryInfo属性作为参数传递,问题是代码只适用于“”顶级“”属性,如“Name”, “Root”,“Drive”等......
但是我需要使用这样的函数:
Dim Folders As List(Of IO.DirectoryInfo) = blah bla blah...
For Each folderinfo In Bubble_Sort_List_DirectoryInfo(Folders, Function() New IO.DirectoryInfo("").Name)
MsgBox(folderinfo.Name)
Next
但是我需要使用像这样的函数:
For Each folderinfo In Bubble_Sort_List_DirectoryInfo(Folders, Function() New IO.DirectoryInfo("").Parent.Name.Length)
MsgBox(folderinfo.Name)
Next
在此功能中添加/修改以管理DirectoryInfo属性的使用是必要的,例如“ Name.Length ”或“ Parent。 Name.Length 的“?
Private Shared Function Bubble_Sort_List_DirectoryInfo(list As List(Of IO.DirectoryInfo), _
exp As Expression(Of Func(Of Object))) _
As List(Of IO.DirectoryInfo)
Dim member As MemberExpression = _
If(TypeOf exp.Body Is UnaryExpression, _
DirectCast(DirectCast(exp.Body, UnaryExpression).Operand, MemberExpression), _
DirectCast(exp.Body, MemberExpression))
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(DirectCast(member.Member, PropertyInfo) _
.GetValue(folder, Nothing), Object).ToString.Length).Max(), _
If(Char.IsDigit(m.Value(0)), " "c, Char.MaxValue))) _
}).OrderBy(Function(x) x.SortStr).Select(Function(x) x.OrgStr).ToList
End Function
更新:
这只是一些解释和例子。
在我的驱动器目录中,我有一些文件夹名称如下:
80's
90's
2000-2006
2007
2008
在我的应用程序中,我使用“IO.Directory.GetDirectories”方法获取文件夹,然后将它们存储到DirectoryInfo()列表中
这是输入列表:
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()
...但是“IO”方法会导致列表内容按字符串排序排序,如下所示:
2000-2006
2007
2008
80's
90's
我想要的输出是:
80's
90's
2000-2006
2007
2008
因此,在使用“IO”方法创建List之后,我需要对列表内容进行排序以获得我想要的输出并且确切地说我使用上面的功能使用属性“Name”作为参数来冒泡按名称属性对文件夹进行排序,因此我得到了我想要的输出。
问题是我需要使用其他属性,如“Name.Length”和“Parent.Name.Length”,但该函数只允许使用“”TopLevel“”“属性,如”Name“, “父”等,但不是变量属性。
答案 0 :(得分:1)
创建一个实现IComparer的类:
Public Class MyDirectoryInfoComparer
Implements IComparer(Of IO.DirectoryInfo)
Public Function Compare(x As IO.DirectoryInfo, y As IO.DirectoryInfo) As Integer _
Implements IComparer(Of IO.DirectoryInfo).Compare
' x comes before y
Return -1 ' or any number less than 0
' x is the same as y
Return 0
' x comes after y
Return 1 ' or any number greater than 0
End Function
创建列表:
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()
然后使用你的comparer类对它进行排序:
Folders.Sort(New MyDirectoryInfoComparer)