Wine Too
Wine Too

Reputation: 4655

How to sort array of FileInfo objects in descending order without LINQ

I have to downgrade my code to be able to work on NET 2.0, which does not support LINQ. Currently, the code sorts an array of FileInfo objects by their FullName property, using LINQ, like this:

    Dim files As FileInfo() = ' ...
    files = files.OrderByDescending(Function(x) x.FullName).ToArray()

How can I perform the same kind of sort in the 2.0 .NET Framework without using the OrderByDescending LINQ extension method?

Upvotes: 3

Views: 5878

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

To sort an array without LINQ, you can use the Array.Sort shared method. If has many overloads that allow you to customize the way the array is sorted. The two overloads that I would recommend, in this case, would be either the one that takes an IComparer(Of T) object, or the one that takes a Comparison(Of T) delegate.

Sort Using IComparer(Of T)

The IComparer(Of T) interface can be used to create re-usable classes that wrap the sorting logic. You can easily sort any array or list using the same IComparer(Of T) class, so it is often more convenient in situations where you need to re-use the same sorting logic in multiple places in your code. First, you need to create the class that implements the interface, like this:

Public Class FileInfoDescendingByNameComparer
    Implements IComparer(Of FileInfo)

    Public Function Compare(x As FileInfo, y As FileInfo) As Integer Implements IComparer(Of FileInfo).Compare
        Return y.FullName.CompareTo(x.FullName)
    End Function
End Class

As you can see, I am using the default comparison logic built into the String class (the FullName property) to perform the comparison. The reason it will sort in descending order is because I am comparing y.FullName to x.FullName rather than comparing x.FullName to y.FullName.

Then, you can sort the array of FileInfo objects using that class, like this:

Array.Sort(Of FileInfo)(files, New FileInfoDescendingByNameComparer())

Sort Using Comparison(Of T)

If you don't need to re-use the sorting logic in multiple places, or, as in this case, the comparison logic is very simple, it is easier to create a Comparison(Of T) delegate to point to an in-line anonymous function, like this:

Array.Sort(Of FileInfo) _
    ( 
    files, 
    New Comparison(Of FileInfo) _
        ( 
        Function(f1 As FileInfo, f2 As FileInfo) f2.FullName.CompareTo(f1.FullName)
        )
    )

Upvotes: 4

Related Questions