List(Of T).Sort Method ()
Sorts the elements in the entire List(Of T) using the default comparer.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| 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 example adds some names to a List<String> object, displays the list in unsorted order, calls the Sort method, and then displays the sorted list.
Imports System.Collections.Generic Module Example Public Sub Main() Dim names() As String = { "Samuel", "Dakota", "Koani", "Saya", "Vanya", "Yiska", "Yuma", "Jody", "Nikita" } Dim nameList As New List(Of String)() nameList.AddRange(names) Console.WriteLine("List in unsorted order: ") For Each name In nameList Console.Write(" {0}", name) Next Console.WriteLine(vbCrLf) nameList.Sort() Console.WriteLine("List in sorted order: ") For Each name In nameList Console.Write(" {0}", name) Next Console.WriteLine() End Sub End Module ' The example displays the following output: ' List in unsorted order: ' Samuel Dakota Koani Saya Vanya Yiska Yuma Jody Nikita ' ' List in sorted order: ' Dakota Jody Koani Nikita Samuel Saya Vanya Yiska Yuma
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
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1