VB.Net Tutorial/Collections/IComparable

Материал из VB Эксперт
Перейти к: навигация, поиск

IComparable

Imports System.Collections
Module Test
    Public Sub Main()
        Dim objEmployee1 As New Employee()
        Dim objEmployee2 As New Employee()
        Dim objEmployee3 As New Employee()
        objEmployee1.FirstName = "A"
        objEmployee1.LastName = "B"
        objEmployee2.FirstName = "C"
        objEmployee2.LastName = "D"
        objEmployee3.FirstName = "E"
        objEmployee3.LastName = "F"
        Dim slPeople As New SortedList()
        slPeople.Add(objEmployee1, 1)
        slPeople.Add(objEmployee2, 2)
        slPeople.Add(objEmployee3, 3)
        Dim objDE As DictionaryEntry
        For Each objDE In slPeople
            Console.WriteLine("{0} {1}",CType(objDE.Key, Employee).DisplayName, CType(objDE.Value,Integer))
        Next
    End Sub
End Module
Public Class Employee
    Implements IComparable
    Public FirstName As String
    Public LastName As String
    Public ReadOnly Property DisplayName() As String
        Get
            Return String.Format("{0} {1}", FirstName, LastName)
        End Get
    End Property
    Public Function CompareTo(ByVal obj As Object) As Integer _
        Implements System.IComparable.rupareTo
        Dim objOtherEmployee As Employee
        objOtherEmployee = CType(obj, Employee)
        If objOtherEmployee.LastName > Me.LastName Then
            Return -1
        ElseIf objOtherEmployee.LastName < Me.LastName Then
            Return 1
        Else
            If objOtherEmployee.FirstName > Me.FirstName Then
                Return -1
            ElseIf objOtherEmployee.FirstName < Me.FirstName Then
                Return 1
            Else
                Return 0
            End If
        End If
    End Function
End Class
A B 1
C D 2
E F 3