自定义日期排序

时间:2017-10-06 17:49:37

标签: vb.net sorting date alphanumeric

我有一个日期值列表

  

10/06 / 2012,4 / 12/12,7/13 / 12,08.02.12,04.05.13,11.27.12

需要按正确的时间顺序排序。

原始数据条目的格式未受控制,因此是可变的。到目前为止,日期分隔符已经显示为“。”和'/'。每个日期段的位数不一致。

此列表表示表中的单列数据。数据是从不同的来源读取的,可以放入任何便于排序的结构中。日期必须对整个表格进行排序。

数据必须保持原始输入状态,因此我不能简单地转换数据并使用它完成。

2 个答案:

答案 0 :(得分:1)

这是一个函数和重载,可以使用您提供的字符串或字符串列表:

Private Function getSortedDates(input As String) As IEnumerable(Of DateTime)
    Return getSortedDates(input.Split({","c}, StringSplitOptions.RemoveEmptyEntries))
End Function

Private Function getSortedDates(input As IEnumerable(Of String)) As IEnumerable(Of DateTime)
    Return input.
        Select(Function(s As String) DateTime.Parse(s.Replace(".", "/"))).
        OrderBy(Function(d) d)
End Function

用法:

Sub Main()
    ' as a string
    Dim input1 = "10/06/2017, 4/20/12, 7/13/12, 08.02.12, 04.05.13, 11.27.12"
    Dim output1 = getSortedDates(input1)
    ' as an array
    Dim input2 = {"10/06/2017", "4/20/12", "7/13/12", "08.02.12", "04.05.13", "11.27.12"}
    Dim output2 = getSortedDates(input2)
    ' output1 and output2 have the same sorted dates.
End Sub

答案 1 :(得分:0)

您可以构建可用于排序的自定义Comparer

Module Module1

    Sub Main()

        Dim dates() As String = {"10/06/2017", "4/20/12", "7/13/12", "08.02.12", "04.05.13", "11.27.12"}

        Array.Sort(dates, New StringDateSorter)

        For Each d In dates
            Console.WriteLine(d)
        Next

    End Sub

End Module

Class StringDateSorter
    Implements IComparer(Of String)

    Public Function Compare(x As String, y As String) As Integer Implements IComparer(Of String).Compare
        Dim d1 = Date.Parse(x)
        Dim d2 = Date.Parse(y)
        Return Date.Compare(d1, d2)

    End Function
End Class
相关问题