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