比较方法:两个不同的类,其中有一个属性是相同类型的,如日期,或者字符。
自定义IComparer,实现比较方法。
imports System.Runtimeimports System.CollectionsPublic 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 SubEnd ClassPublic 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 FunctionEnd 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 FunctionEnd ClassPublic 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 FunctionEnd Class
对比结果:
总结以上是内存溢出为你收集整理的VB.Net程序设计:IComparer的应用,按两个不同类的某个属性比较排序全部内容,希望文章能够帮你解决VB.Net程序设计:IComparer的应用,按两个不同类的某个属性比较排序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)