在带有对象的列上对 .Net 数据表进行排序

时间:2021-01-14 14:08:39

标签: .net vb.net datatable

我正在尝试对 DataTable 进行排序,其中某些列可能是自定义对象。该对象实现了 IComparable 接口。

Dim lView As DataView = lExport.DefaultView
lView.Sort = "ColA, ColB"
lExport = lView.ToTable()

ColB 是一个实现 IComparable 的对象。

Public Class DataLite
    Implements IComparable(Of DataLite)
    Public Property Value As Object
    Public Property Updated As Date?
    Public Property Options As Integer
    Public Property DataType As DataDefClass.DefDataType
    Public Property Format As String

    ' More fields and methods excluded 
End Class

当我设置 lView.Sort = "ColA, ColB" 时,出现错误 - 未将对象引用设置为对象的实例

列中的某些对象可能具有空值。我该如何实现?

编辑:这是 IComparable 实现:

Public Function CompareTo(other As DataLite) As Integer Implements IComparable(Of DataLite).CompareTo
    If TypeOf (_Value) Is Date AndAlso TypeOf (other.Value) Is Date Then
        If CDate(_Value) < CDate(other.Value) Then Return -1
        If CDate(_Value) = CDate(other.Value) Then Return 0
        Return 1
    ElseIf Decimal.TryParse(Convert.ToString(_Value), Nothing) AndAlso Decimal.TryParse(Convert.ToString(other.Value), Nothing) Then
        If CDec(_Value) < CDec(other.Value) Then Return -1
        If CDec(_Value) = CDec(other.Value) Then Return 0
        Return 1
    ElseIf _Value Is Nothing Then
        Return -1
    ElseIf other.Value Is Nothing Then
        Return 1
    Else
        Return _Value.ToString.CompareTo(other.Value.ToString)
    End If
End Function

0 个答案:

没有答案
相关问题