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

Home
VB.Net Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statements
5.Date Time
6.Class Module
7.Development
8.Collections
9.Generics
10.Attributes
11.Event
12.LINQ
13.Stream File
14.GUI
15.GUI Applications
16.Windows Presentation Foundation
17.2D Graphics
18.I18N Internationlization
19.Reflection
20.Regular Expressions
21.Security
22.Socket Network
23.Thread
24.Windows
25.XML
26.Database ADO.net
27.Design Patterns
VB.Net
VB.Net by API
VB.Net Tutorial » Generics » Generic List 
9.4.2.Sort(IComparer<(Of <(T>)>)) and the BinarySearch(T, IComparer<(Of <(T>)>))
Imports System
Imports System.Collections.Generic

Public Class LetterComparer
    Implements IComparer(Of String)

    Public Function Compare(ByVal x As String,ByVal y As StringAs 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 <> 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 < 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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.