IComparer(Of T) 接口的实现 (vb.net)

这个博客介绍了一个自定义的IComparer<T>实现,用于VB.NET中按特定属性进行列表排序。该实现考虑了日期、整数、小数和字符串类型的比较,并提供了升序和降序排列的选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Imports Microsoft.VisualBasic
  2. Imports System.Collections.Generic
  3. Imports System.Reflection
  4. Public Class IListComparer(Of T)
  5.     Implements IComparer(Of T)
  6.     Private mpropertyName As String
  7.     Private mIsAsc As Boolean
  8.     Public Property PropertyName() As String
  9.         Get
  10.             Return mpropertyName
  11.         End Get
  12.         Set(ByVal value As String)
  13.             mpropertyName = value
  14.         End Set
  15.     End Property
  16.     Public Property IsAsc() As Boolean
  17.         Get
  18.             Return mIsAsc
  19.         End Get
  20.         Set(ByVal value As Boolean)
  21.             mIsAsc = value
  22.         End Set
  23.     End Property
  24.     Public Sub New(ByVal propertyName As StringByVal IsAsc As Boolean)
  25.         mIsAsc = IsAsc
  26.         mpropertyName = propertyName
  27.     End Sub
  28.     Public Function Compare(ByVal x As T, ByVal y As T) As Integer Implements System.Collections.Generic.IComparer(Of T).Compare
  29.         Dim pro As PropertyInfo = GetType(T).GetProperty(Me.PropertyName)
  30.         Dim result As Integer = 0
  31.         Select Case pro.PropertyType.Name.ToUpper
  32.             Case "DATE""DATETIME"
  33.                 result = Date.Compare(pro.GetValue(x, Nothing), pro.GetValue(y, Nothing))
  34.             Case "INT32""INTEGER""INT32"
  35.                 result = Integer.Parse(pro.GetValue(x, Nothing)).CompareTo(Integer.Parse(pro.GetValue(y, Nothing)))
  36.             Case "DECIMAL"
  37.                 result = Decimal.Compare(pro.GetValue(x, Nothing), pro.GetValue(y, Nothing))
  38.             Case Else
  39.                 result = String.Compare(pro.GetValue(x, Nothing), pro.GetValue(y, Nothing), True)
  40.         End Select
  41.         If result = 0 Then
  42.             Return result
  43.         ElseIf IsAsc Then
  44.             Return (-1) * result
  45.         End If
  46.         Return result
  47.     End Function
  48. End Class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值