Sunday, May 17, 2009
at
10:49 PM
Posted by
牛奶罐
- I will create Customer object
Class Customer
Private _Name As String
Private _Age As Integer
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal value As Integer)
_Age = value
End Set
End Property
End Class
- Add two compare methods , one for compare by name, and one for compare by age
Class Customer
Private _Name As String
Private _Age As Integer
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal value As Integer)
_Age = value
End Set
End Property
Public Shared Function CompareByName(ByVal c1 As Customer, _
ByVal c2 As Customer) As Integer
Return c1.Name.CompareTo(c2.Name)
End Function
Public Shared Function CompareByAge(ByVal c1 As Customer, _
ByVal c2 As Customer) As Integer
Return c1.Age.CompareTo(c2.Age)
End Function
End Class
- Create a Collection with generic List(T)
Dim CustList As New List(Of Customer)
cus1 = New Customer()
cus1.Name = "B"
cus1.Age = 23
CustList.Add(cus1)
cus2 = New Customer()
cus2.Name = "A"
cus2.Age = 24
CustList.Add(cus2)
cus3 = New Customer()
cus3.Name = "C"
cus3.Age = 27
CustList.Add(cus3)
- To use the List.Sort(Generic Comparison) create a instance of Comparison delegate and register it with CompareByName and CompareByAge method.
Dim comp1 As New Comparison(Of Customer)(Customer.CompareByName)
CustList.Sort(comp1)
For Each cus As Customer In CustList
Console.WriteLine((cus.Name & " ") + cus.Age)
Next
Dim comp2 As New Comparison(Of Customer)(Customer.CompareByAge)
CustList.Sort(comp2)
For Each cus As Customer In CustList
Console.WriteLine((cus.Name & " ") + cus.Age)
Next
0 comments:
Post a Comment