VB.Net程序设计:IComparer的应用,按两个不同类的某个属性比较排序

前端之家收集整理的这篇文章主要介绍了VB.Net程序设计:IComparer的应用,按两个不同类的某个属性比较排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

比较方法:两个不同的类,其中有一个属性是相同类型的,如日期,或者字符。

自定义IComparer,实现比较方法

Imports System.Runtime
Imports System.Collections

Public Class Form1

    Private Sub Button1_Click(sender As System.Object,e As System.EventArgs) Handles Button1.Click
        Dim ArList As New ArrayList
        With ArList
            .Add(New Duty(Date.Now,"now"))
            .Add(New DutyTemp(Date.Today,"today"))
            .Add(New Duty(Date.Today.AddHours(1),"today+1h"))
            .Add(New DutyTemp(Date.Today.AddDays(1),"today-1day"))
            .Add(New Duty(Date.Today.AddHours(-1),"today-1h"))
            .Add(New Duty(Date.Today.AddDays(5),"today-5day"))
            .Add(New DutyTemp(Date.Today.AddDays(-8),"today-8day"))
        End With
        ArList.Sort(New DutyComparer)
        For Each obj As Object In ArList
            Debug.Print(obj.ToString)
        Next
    End Sub

End Class

Public Class DutyComparer
    Implements IComparer

    Public Function Compare(x As Object,y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim dtm1,dtm2 As Date
        Select Case x.GetType
            Case GetType(Duty)
                dtm1 = CType(x,Duty).DateFrom
            Case GetType(DutyTemp)
                dtm1 = CType(x,DutyTemp).TimeFrom
        End Select
        Select Case y.GetType
            Case GetType(Duty)
                dtm2 = CType(y,Duty).DateFrom
            Case GetType(DutyTemp)
                dtm2 = CType(y,DutyTemp).TimeFrom
        End Select
        Return Date.Compare(dtm1,dtm2)
    End Function
End Class

'--如果兩個不同類可以抽象處理,實現相同接口,就比較容易點。
Public Class Duty

    Property DateFrom As Date
    Property DutyName As String

    Sub New(dtmFrom As Date,strName As String)
        DateFrom = dtmFrom
        DutyName = strName
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("{0}-{1}",DateFrom.ToString,DutyName)
    End Function

End Class

Public Class DutyTemp

    Property TimeFrom As Date
    Property DutyTempName As String

    Sub New(dtmFrom As Date,strName As String)
        TimeFrom = dtmFrom
        DutyTempName = strName
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("{0}-{1}",TimeFrom.ToString,DutyTempName)
    End Function

End Class


对比结果:

猜你在找的VB相关文章