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

好久不见. 提交于 2019-12-24 00:19:28

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15135508/how-to-sort-array-of-fileinfo-objects-in-descending-order-without-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!