0

I am stuck on this sorting problem.

    Private Sub ...
        Dim oDirInfo As DirectoryInfo
        Dim aoFSInfo() As FileSystemInfo
        Dim asFiles() As String

FQPN is a fully qualified path name ending in "\*.*".

        oDirInfo = New DirectoryInfo(FQPN)

Now into asFiles I want the files' names, sorted by the files' timestamps in ascending order. I presume, that oDirInfo.CreationTime plays a role here, but can not figure out how to use OrderBy properly.

        aoFSInfo = oDirInfo.GetFileSystemInfos()    '?
        asFiles = aoFSInfo.OrderBy(...)
    End Sub

1 Answers1

1

Yes, that's LINQ and you can use this (method-)syntax:

asFiles = oFSInfo.
    OrderBy(Function(fsi) fsi.CreationTime).
    Select(Function(fsi) fsi.FullName).
    ToArray()

If you don't like the ugly Function keyword you can use query syntax:

Dim orderedFiles = From fsi In oFSInfo
                   Order by fsi.iCreationTime Ascending
                   Select fsi.FullName
asFiles = orderedFiles.ToArray()

Even if these are two statements it's not slower than method syntax due to deferred execution.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • When using the query syntax you can put () around the query and append .ToArray. – dbasnett Jun 19 '17 at 10:58
  • @dbasnett: yes, but that would destroy readability which was the reason to split it into two. There is no reason to avoid a second statement. It even enables to reuse the query if desired. – Tim Schmelter Jun 19 '17 at 11:05
  • @TimSchmelter. Small typo I can't correct due to being just 3 letters in total. Twice cosmetical: `oFSInfo` instead of `aoFSInfo` to reflect the variable in the OP; once syntactical: the member `iCreationTime` should read `CreationTime`. - Maybe not too important, but I'd probably go for the full declaration `Dim orderedFiles As IEnumerable(Of String) ...` - Otherwise: Thanks for your answer. –  Jun 20 '17 at 02:52