user2737085 user2737085 - 4 months ago 10 Question

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

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 soon as I get a solution!!)?
Thanks for your help!!


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). _

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.