Sort(IComparer<(Of <(T>)>)) and the BinarySearch(T, IComparer<(Of <(T>)>)) : Generic List « Generics « VB.Net Tutorial






Imports System
Imports System.Collections.Generic

Public Class LetterComparer
    Implements IComparer(Of String)

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

        If x Is Nothing Then
            If y Is Nothing Then 
                Return 0
            Else
                Return -1
            End If
        Else
            If y Is Nothing Then
                Return 1
            Else
                Dim retval As Integer = x.Length.CompareTo(y.Length)
                If retval <> 0 Then 
                    Return retval
                Else
                    Return x.CompareTo(y)
                End If
            End If
        End If
    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim letters As New List(Of String)
        letters.Add("A")
        letters.Add("B")
        letters.Add("C")
        letters.Add("D")
        Display(letters)

        Dim dc As New LetterComparer

        letters.Sort(dc)
        Display(letters)

        SearchAndInsert(letters, "E", dc)
        Display(letters)

        SearchAndInsert(letters, Nothing, dc)
        Display(letters)
    End Sub

    Private Shared Sub SearchAndInsert(ByVal lis As List(Of String),ByVal insert As String, ByVal dc As LetterComparer)
        Dim index As Integer = lis.BinarySearch(insert, dc)

        If index < 0 Then
            index = index Xor -1
            lis.Insert(index, insert)
        End If
    End Sub

    Private Shared Sub Display(ByVal lis As List(Of String))
        Console.WriteLine()
        For Each s As String In lis
            Console.WriteLine(s)
        Next
    End Sub
End Class








9.4.Generic List
9.4.1.Use generic List
9.4.2.Sort(IComparer<(Of <(T>)>)) and the BinarySearch(T, IComparer<(Of <(T>)>))
9.4.3.Generic list of user objects