Implements IComparer to create Reversed Comparer : IComparer « Collections « VB.Net Tutorial






Imports System
Imports System.Collections.Generic

Public Class ReverseComparer
    Implements IComparer(Of String)
    Public Function Compare(ByVal x As String, _
        ByVal y As String) As Integer _
        Implements IComparer(Of String).Compare
        Return y.CompareTo(x)

    End Function
End Class

Public Class Example
    Public Shared Sub Main()

        Dim employees() As String = {"A","B","E","C","F","G"  }

        Dim employeeSizes() As Integer = { 40, 5, 3, 22, 1, 18 }

        For i As Integer = 0 To employees.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", employees(i), employeeSizes(i))
        Next

        Console.WriteLine("Sort(employees, employeeSizes)")
        Array.Sort(employees, employeeSizes)

        For i As Integer = 0 To employees.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                employees(i), employeeSizes(i))
        Next

        Dim rc As New ReverseComparer()

        Console.WriteLine("Sort(employees, employeeSizes, rc)")
        Array.Sort(employees, employeeSizes, rc)

        Console.WriteLine()
        For i As Integer = 0 To employees.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.",employees(i), employeeSizes(i))
        Next

        Console.WriteLine("Sort(employees, employeeSizes, 3, 3)")
        Array.Sort(employees, employeeSizes, 3, 3)

        Console.WriteLine()
        For i As Integer = 0 To employees.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.",employees(i), employeeSizes(i))
        Next

        Console.WriteLine("Sort(employees, employeeSizes, 3, 3, rc)")
        Array.Sort(employees, employeeSizes, 3, 3, rc)

        Console.WriteLine()
        For i As Integer = 0 To employees.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.",employees(i), employeeSizes(i))
        Next


    End Sub

End Class








8.21.IComparer
8.21.1.Implements IComparer
8.21.2.Use custom Comparer to compare objects
8.21.3.Implements IComparer to create Reversed Comparer