Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

List(Of T).Sort Method (IComparer(Of T))

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

Namespace:  System.Collections.Generic
Assemblies:   mscorlib (in mscorlib.dll)
  System.Collections (in System.Collections.dll)

'Declaration
Public Sub Sort ( _
	comparer As IComparer(Of T) _
)

Parameters

comparer
Type: System.Collections.Generic.IComparer(Of T)

The IComparer(Of T) implementation to use when comparing elements, or Nothing to use the default comparer Comparer(Of T).Default.

ExceptionCondition
InvalidOperationException

comparer is Nothing, and the default comparer Comparer(Of T).Default cannot find implementation of the IComparable(Of T) generic interface or the IComparable interface for type T.

ArgumentException

The implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself.

If comparer is provided, the elements of the List(Of T) are sorted using the specified IComparer(Of T) implementation.

If comparer is Nothing, the default comparer Comparer(Of T).Default 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 example demonstrates the Sort(IComparer(Of T)) method overload and the BinarySearch(T, IComparer(Of T)) method overload.

The example defines an alternative comparer for strings named DinoCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. The comparer works as follows: First, the comparands are tested for Nothing, and a null reference is treated as less than a non-null. Second, the string lengths are compared, and the longer string is deemed to be greater. Third, if the lengths are equal, ordinary string comparison is used.

A List(Of T) of strings is created and populated with four strings, in no particular order. The list is displayed, sorted using the alternate comparer, and displayed again.

The BinarySearch(T, IComparer(Of T)) method overload is then used to search for several strings that are not in the list, employing the alternate comparer. The Insert method is used to insert the strings. These two methods are located in the function named SearchAndInsert, along with code to take the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of the negative number returned by BinarySearch(T, IComparer(Of T)) and use it as an index for inserting the new string.

Imports System
Imports System.Collections.Generic

Public Class DinoComparer
    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  
                ' If x is Nothing and y is Nothing, they're 
                ' equal.  
                Return 0
            Else 
                ' If x is Nothing and y is not Nothing, y 
                ' is greater.  
                Return -1
            End If 
        Else 
            ' If x is not Nothing... 
            
            If y Is Nothing Then 
                ' ...and y is Nothing, x is greater. 
                Return 1
            Else 
                ' ...and y is not Nothing, compare the  
                ' lengths of the two strings. 
                
                Dim retval As Integer = _
                    x.Length.CompareTo(y.Length)

                If retval <> 0 Then  
                    ' If the strings are not of equal length, 
                    ' the longer string is greater. 
                    
                    Return retval
                Else 
                    ' If the strings are of equal length, 
                    ' sort them with ordinary string comparison. 
                    
                    Return x.CompareTo(y)
                End If 
            End If 
        End If 
    End Function 
End Class 

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")
        Display(dinosaurs)

        Dim dc As New DinoComparer

        Console.WriteLine(vbLf & "Sort with alternate comparer:")
        dinosaurs.Sort(dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Coelophysis", dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Oviraptor", dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Tyrannosaur", dc)
        Display(dinosaurs)

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

    Private Shared Sub SearchAndInsert( _
        ByVal lis As List(Of String), _
        ByVal insert As String, ByVal dc As DinoComparer)

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""{0}"":", insert)

        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 

' This code example produces the following output: 

'Pachycephalosaurus 
'Amargasaurus 
'Mamenchisaurus 
'Deinonychus 

'Sort with alternate comparer: 

'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "Coelophysis": 

'Coelophysis 
'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "Oviraptor": 

'Oviraptor 
'Coelophysis 
'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "Tyrannosaur": 

'Oviraptor 
'Coelophysis 
'Deinonychus 
'Tyrannosaur 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 

'BinarySearch and Insert "": 


'Oviraptor 
'Coelophysis 
'Deinonychus 
'Tyrannosaur 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Show:
© 2015 Microsoft