FileInfoComparer未正确排序(在LastWriteTime上)

时间:2011-12-22 14:44:39

标签: .net vb.net sorting directoryinfo

我有一个简单的(ASP.NET)网页,列出文件夹中特定类型的文件,并在ListView中呈现它们。

我试图通过降序LastWriteTime对它们进行排序,即以反向日期顺序排序。但是,尽管排序过程确实会更改数组的顺序,但它并未对其进行正确排序。例如,一个LastWriteTime为#6/3/2011 12:00:00的项目位于列表顶部,但LastWriteTime为#12/16/2011 12:00:00的另一个项目在排序后位于列表的中间位置。

任何想法为什么?

代码:

        Dim dirInfo As New DirectoryInfo(Server.MapPath(AppSettings.Item("ContentDir")))
        Dim FileArrayList As New ArrayList(dirInfo.GetFiles("*.msg", SearchOption.TopDirectoryOnly))

        Dim SortDirections As New Dictionary(Of String, SqlClient.SortOrder)

        With FileArrayList
            .TrimToSize()
            .Sort(New FileInfoComparer(SqlClient.SortOrder.Descending, "LastWriteTime"))
        End With

FileInforComparer类:

Imports System.IO
Imports System.Reflection


Public Class FileInfoComparer
    Implements IComparer

    Private _sortOrder As System.Data.SqlClient.SortOrder
    Private _sortColumn As String

    ''' <summary>
    ''' Constructs new Comparer object, using the supplied SortOrder and SortColumn parameters
    ''' </summary>
    ''' <param name="sortOrder">Defines the SortOrder for the comparison</param>
    ''' <param name="sortColumn">Defines which column is sorted</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal sortOrder As System.Data.SqlClient.SortOrder, ByVal sortColumn As String)
        _sortOrder = sortOrder
        _sortColumn = sortColumn
    End Sub


    ''' <summary>
    ''' Defines the Sorting mechanism for FileInfo objects
    ''' </summary>
    ''' <param name="x">First FileInfo object to compare</param>
    ''' <param name="y">Second FileInfo object to compare</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Overridable Overloads Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare

        Dim oX_PI As PropertyInfo = CType(x, FileInfo).GetType.GetProperty(_sortColumn)
        Dim oY_PI As PropertyInfo = CType(y, FileInfo).GetType.GetProperty(_sortColumn)
        Dim Result As Int16 = oX_PI.GetValue(x, Nothing).CompareTo(oY_PI.GetValue(x, Nothing))

        'If DESC then reverse the result
        If _sortOrder = SqlClient.SortOrder.Descending Then Result = Result * -1

        Return Result

    End Function
End Class

2 个答案:

答案 0 :(得分:3)

LastWriteTime可以作为字符串返回,这解释了排序顺序。值按字符串排序,而不是DateTime对象。将字符串解析为datetime,排序顺序应正确。

答案 1 :(得分:1)

这是一个使用LINQ的解决方案。这是用C#和converted编写的VB,所以希望这有效。

Dim dirInfo = New DirectoryInfo(Server.MapPath(AppSettings.Item("ContentDir")))
Dim fileList = dirInfo.GetFiles("*.msg", SearchOption.TopDirectoryOnly).OrderByDescending(Function(f) f.LastWriteTime)

fileList的类型为IEnumerable<FileInfo>。如果您需要它是一个可变列表,而不是使用ArrayList,我建议使用List<FileInfo>,这可以通过添加.ToList()来结束,就像这样

Dim fileList = dirInfo.GetFiles("*.msg", SearchOption.TopDirectoryOnly).OrderByDescending(Function(f) f.LastWriteTime).ToList()