Search code examples
vb.netsortinggetfiles

Using Directory.GetFiles() WITH multiple extensions AND sort order


I have to get a directory file list, filtered on multiple extensions...and sorted!

I use this, which is the fastest way I've found to get dir content filtered on multiple extensions:

Dim ext As String() = {"*.jpg", "*.bmp","*png"}
Dim files As String() = ext.SelectMany(Function(f) Directory.GetFiles(romPath, f)).ToArray
Array.Sort(files)

and then use an array sort.

I was wondering (and this is my question ;)) if there would be a way to do the sorting IN the same main line? A kind of:

Dim files As String() = ext.SelectMany(Function(f) Directory.GetFiles(romPath, f).**Order By Name**).ToArray

and, if yes, if I would gain speed doing this instead of sorting the array at the end (but I would do my test and report..as soon as I get a solution!!)? Thanks for your help!!


Solution

  • You can use the OrderBy() Linq extension method, like this:

        Dim ext = {"*.jpg", "*.bmp", "*png"}
        Dim files = ext.SelectMany(Function(f) Directory.GetFiles(romPath, f)). _
                    OrderBy(Function(f) f). _
                    ToArray()
    

    It won't make any difference for speed, sorting is inherently O(nlog(n)) complexity. It does make a diffence in storage, OrderBy() has O(n) storage requirement. Array.Sort() sorts in-place. Not a big deal for small n values, like you'd expect on a disk directory.