BindingSource.Sort 关于 VB.NET 中的结构

BindingSource.Sort on Structures in VB.NET

我有一个 Structure 和两个 Dates,一个 Sub New 和一个 Function ToString()。我还有一个 DataGridView,绑定到 BindingSource,绑定到 DataTable containing objects of my structure。我现在使用 BindingSource.Sort 来订购我的 DataGridView。 BindingSource 如何对我的 Structure 对象进行排序(看起来像按 String?),我该如何调整它?我是否必须调整结构、继承 BindingSource-Class 或如何开始?

ps。这个结构只是一个例子。我将来可能会有更复杂的。

Public Structure dateRange
    Public date1 As Date
    Public date2 As Date
    Sub New(newdt1 As Date, newdt2 As Date)
        date1=newdt1
        date2=newdt2
    End Sub
    Public Overrides Function ToString() As String
        Return date1.ToString & " - " & date2.ToString
    End Function
End Structure

如果你想让一个类型有一个默认的排序模式,那么你需要实现 IComparable and/or IComparable(Of T) 接口。实施两者被认为是好的做法。例如

Public Structure DateRange
    Implements IComparable, IComparable(Of DateRange)

    Public ReadOnly Property StartDate As Date
    Public ReadOnly Property EndDate As Date

    Public Sub New(startDate As Date, endDate As Date)
        Me.StartDate = startDate
        Me.EndDate = endDate
    End Sub

    Public Overrides Function ToString() As String
        Return $"{StartDate} - {EndDate}"
    End Function

    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
        Return CompareTo(DirectCast(obj, DateRange))
    End Function

    Public Function CompareTo(other As DateRange) As Integer Implements IComparable(Of DateRange).CompareTo
        'Sort by start date by default.
        Dim result = StartDate.CompareTo(other.StartDate)

        If result = 0 Then
            'Start dates are the same so sort by end date.
            result = EndDate.CompareTo(other.EndDate)
        End If

        Return result
    End Function

End Structure

请注意,此实现利用 Date 类型提供的实现来完成繁重的工作。

您可以阅读有关排序列表的更多信息here