Export (0) Print
Expand All
8 out of 15 rated this helpful - Rate this topic

List(Of T).Sort Method

Sorts the elements in the entire List(Of T) using the default comparer.

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)
'Declaration
Public Sub Sort
ExceptionCondition
InvalidOperationException

The default comparer Comparer(Of T).Default cannot find an implementation of the IComparable(Of T) generic interface or the IComparable interface for type T.

This method uses the default comparer Comparer(Of T).Default for type T to determine the order of list elements. The Comparer(Of T).Default property checks whether type T implements the IComparable(Of T) generic interface and uses that implementation, if available. If not, Comparer(Of T).Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer(Of T).Default throws an InvalidOperationException.

This method uses the Array.Sort method, which applies the introspective sort as follows:

  • If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Otherwise, it uses a Quicksort algorithm.

This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.

The following code demonstrates the Sort and Sort(Comparison(Of T)) method overloads on a simple business object. Calling the Sort method results in the use of the default comparer for the Part type, and the Sort(Comparison(Of T)) method is implemented by using an anonymous method.

Imports System.Collections.Generic
' Simple business object. A PartId is used to identify the type of part  
' but the part name can change.  
Public Class Part
    Implements IEquatable(Of Part)
    Implements IComparable(Of Part)
    Public Property PartName() As String 
        Get 
            Return m_PartName
        End Get 
        Set(value As String)
            m_PartName = Value
        End Set 
    End Property 
    Private m_PartName As String 

    Public Property PartId() As Integer 
        Get 
            Return m_PartId
        End Get 
        Set(value As Integer)
            m_PartId = Value
        End Set 
    End Property 
    Private m_PartId As Integer 

    Public Overrides Function ToString() As String 
        Return "ID: " & PartId & "   Name: " & PartName
    End Function 

    Public Overrides Function Equals(obj As Object) As Boolean 
        If obj Is Nothing Then 
            Return False 
        End If 
        Dim objAsPart As Part = TryCast(obj, Part)
        If objAsPart Is Nothing Then 
            Return False 
        Else 
            Return Equals(objAsPart)
        End If 
    End Function 

    Public Function SortByNameAscending(name1 As String, name2 As String) As Integer 

        Return name1.CompareTo(name2)
    End Function 

    ' Default comparer for Part. 
    Public Function CompareTo(comparePart As Part) As Integer _
            Implements IComparable(Of ListSortVB.Part).CompareTo
        ' A null value means that this object is greater. 
        If comparePart Is Nothing Then 
            Return 1
        Else 

            Return Me.PartId.CompareTo(comparePart.PartId)
        End If 
    End Function 
    Public Overrides Function GetHashCode() As Integer 
        Return PartId
    End Function 
    Public Overloads Function Equals(other As Part) As Boolean Implements IEquatable(Of ListSortVB.Part).Equals
        If other Is Nothing Then 
            Return False 
        End If 
        Return (Me.PartId.Equals(other.PartId))
    End Function 
    ' Should also override == and != operators. 

End Class 
Public Class Example
    Public Shared Sub Main()
        ' Create a list of parts. 
        Dim parts As New List(Of Part)()

        ' Add parts to the list.
        parts.Add(New Part() With { _
             .PartName = "regular seat", _
             .PartId = 1434 _
        })
        parts.Add(New Part() With { _
             .PartName = "crank arm", _
             .PartId = 1234 _
        })
        parts.Add(New Part() With { _
             .PartName = "shift lever", _
             .PartId = 1634 _
        })


        ' Name intentionally left null.
        parts.Add(New Part() With { _
             .PartId = 1334 _
        })
        parts.Add(New Part() With { _
             .PartName = "banana seat", _
             .PartId = 1444 _
        })
        parts.Add(New Part() With { _
             .PartName = "cassette", _
             .PartId = 1534 _
        })


        ' Write out the parts in the list. This will call the overridden  
        ' ToString method in the Part class.
        Console.WriteLine(vbLf & "Before sort:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next 


        ' Call Sort on the list. This will use the  
        ' default comparer, which is the Compare method  
        ' implemented on Part.
        parts.Sort()


        Console.WriteLine(vbLf & "After sort by part number:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next 

        ' This shows calling the Sort(Comparison(T) overload using  
        ' an anonymous delegate method.  
        ' This method treats null as the lesser of two values.
        parts.Sort(Function(x As Part, y As Part)
                             If x.PartName Is Nothing AndAlso y.PartName Is Nothing Then 
                                 Return 0
                             ElseIf x.PartName Is Nothing Then 
                                 Return -1
                             ElseIf y.PartName Is Nothing Then 
                                 Return 1
                             Else 
                                 Return x.PartName.CompareTo(y.PartName)
                             End If 
                         End Function)


        Console.WriteLine(vbLf & "After sort by name:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next 

        
        '         
        '            Before sort: 
        '            ID: 1434   Name: regular seat 
        '            ID: 1234   Name: crank arm 
        '            ID: 1634   Name: shift lever 
        '            ID: 1334   Name: 
        '            ID: 1444   Name: banana seat 
        '            ID: 1534   Name: cassette 
        
        '            After sort by part number: 
        '            ID: 1234   Name: crank arm 
        '            ID: 1334   Name: 
        '            ID: 1434   Name: regular seat 
        '            ID: 1444   Name: banana seat 
        '            ID: 1534   Name: cassette 
        '            ID: 1634   Name: shift lever 
        
        '            After sort by name: 
        '            ID: 1334   Name: 
        '            ID: 1444   Name: banana seat 
        '            ID: 1534   Name: cassette 
        '            ID: 1234   Name: crank arm 
        '            ID: 1434   Name: regular seat 
        '            ID: 1634   Name: shift lever 

    End Sub 
End Class

The following example demonstrates the Sort method overload and the BinarySearch(T) method overload. A List(Of T) of strings is created and populated with four strings, in no particular order. The list is displayed, sorted, and displayed again.

The BinarySearch(T) method overload is then used to search for two strings that are not in the list, and the Insert method is used to insert them. The return value of the BinarySearch method is negative in each case, because the strings are not in the list. Taking the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of this negative number produces the index of the first element in the list that is larger than the search string, and inserting at this location preserves the sort order. The second search string is larger than any element in the list, so the insertion position is at the end of the list.

Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)

        dinosaurs.Add("Pachycephalosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Sort")
        dinosaurs.Sort

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Coelophysis"":")
        Dim index As Integer = dinosaurs.BinarySearch("Coelophysis")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Coelophysis")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Tyrannosaurus"":")
        index = dinosaurs.BinarySearch("Tyrannosaurus")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Tyrannosaurus")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next 

    End Sub 
End Class 

' This code example produces the following output: 

'Pachycephalosaurus 
'Amargasaurus 
'Mamenchisaurus 
'Deinonychus 

'Sort 

'Amargasaurus 
'Deinonychus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "Coelophysis": 

'Amargasaurus 
'Coelophysis 
'Deinonychus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "Tyrannosaurus": 

'Amargasaurus 
'Coelophysis 
'Deinonychus 
'Mamenchisaurus 
'Pachycephalosaurus 
'Tyrannosaurus

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.