多种参数排序说明
’定义一个类
Public Class ClsSort
Implements IComparable '必须要是继续的
Private mvarid As Integer
Public Property ID() As Integer
Get
Return mvarid
End Get
Set(ByVal value As Integer)
mvarid = value
End Set
End Property
Private mvarName As String
Public Property Name() As String
Get
Return mvarName
End Get
Set(ByVal value As String)
mvarName = value
End Set
End Property
Private mvarOther As String
Public Property Other() As String
Get
Return mvarOther
End Get
Set(ByVal value As String)
mvarOther = value
End Set
End Property
Sub New()
End Sub
Sub New(ByVal pId As Integer, ByVal pName As String, ByVal pOther As String)
mvarid = pId
mvarName = pName
mvarOther = pOther
End Sub
Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
Dim mTemp As ClsSort = CType(obj, ClsSort)
If Me.mvarid > mTemp.mvarid Then
Return 1
ElseIf Me.mvarid < mTemp.mvarid Then
Return -1
Else
Return 0
End If
End Function
Public Class NameComparer
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim c1 As ClsSort = CType(x, ClsSort)
Dim c2 As ClsSort = CType(y, ClsSort)
Return String.Compare(c1.Name, c2.Name)
End Function
End Class
Public Class OtherComparer
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim c1 As ClsSort = CType(x, ClsSort)
Dim c2 As ClsSort = CType(y, ClsSort)
Return String.Compare(c1.Other, c2.Other)
End Function
End Class
Public Shared ReadOnly Property SortByName() As IComparer
Get
Return New NameComparer
End Get
End Property
Public Shared ReadOnly Property SortByOther() As IComparer
Get
Return New OtherComparer
End Get
End Property
End Class
'''测试方法
Dim myAuto(4) As ClsSort
myAuto(0) = New ClsSort(1, "aa", "zz")
myAuto(1) = New ClsSort(22, "bb", "xx")
myAuto(2) = New ClsSort(3, "cc", "yy")
myAuto(3) = New ClsSort(4, "ee", "hh")
myAuto(4) = New ClsSort(52, "dd", "aa")
Console.WriteLine("----before sort-----")
For Each c As ClsSort In myAuto
Console.WriteLine("序号:{0},名称:{1},其它:{2}", c.ID, c.Name, c.Other)
Next
Console.WriteLine()
Array.Sort(myAuto)
' Array.Reverse(myAuto)
Console.WriteLine("----after sort by ID-----")
For Each c As ClsSort In myAuto
Console.WriteLine("序号:{0},名称:{1},其它:{2}", c.ID, c.Name, c.Other)
Next
Console.WriteLine()
'Array.Sort(myAuto, New ClsSort.NameComparer)
Array.Sort(myAuto, ClsSort.SortByName)
Console.WriteLine("----after sor by Name-----")
For Each c As ClsSort In myAuto
Console.WriteLine("序号:{0},名称:{1},其它:{2}", c.ID, c.Name, c.Other)
Next
Console.WriteLine()
' Array.Sort(myAuto, New ClsSort.OtherComparer)
Array.Sort(myAuto, ClsSort.SortByOther)
Console.WriteLine("----after sor by Other-----")
For Each c As ClsSort In myAuto
Console.WriteLine("序号:{0},名称:{1},其它:{2}", c.ID, c.Name, c.Other)
Next
Console.WriteLine()