List<T>.Sort Methode
Definition
Sortiert die Elemente oder einen Teil der Elemente in List<T>, entweder über die angegebene oder eine Standardimplementierung von IComparer<T> oder über einen bereitgestellten Comparison<T>-Delegat zum Vergleichen von Listenelementen.Sorts the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
Überlädt
Sort(Comparison<T>) |
Sortiert die Elemente in der gesamten List<T> mithilfe des angegebenen Comparison<T>.Sorts the elements in the entire List<T> using the specified Comparison<T>. |
Sort(Int32, Int32, IComparer<T>) |
Sortiert die Elemente in einem Bereich von Elementen in der List<T> mithilfe des angegebenen Vergleichs.Sorts the elements in a range of elements in List<T> using the specified comparer. |
Sort() |
Sortiert die Elemente in der gesamten List<T> mithilfe des Standardcomparers.Sorts the elements in the entire List<T> using the default comparer. |
Sort(IComparer<T>) |
Sortiert die Elemente in der gesamten List<T> mithilfe des angegebenen Comparers.Sorts the elements in the entire List<T> using the specified comparer. |
Sort(Comparison<T>)
Sortiert die Elemente in der gesamten List<T> mithilfe des angegebenen Comparison<T>.Sorts the elements in the entire List<T> using the specified Comparison<T>.
public:
void Sort(Comparison<T> ^ comparison);
public void Sort (Comparison<T> comparison);
member this.Sort : Comparison<'T> -> unit
Public Sub Sort (comparison As Comparison(Of T))
Parameter
- comparison
- Comparison<T>
Die Comparison<T>, die beim Vergleich von Elementen verwendet werden soll.The Comparison<T> to use when comparing elements.
Ausnahmen
comparison
ist null
.comparison
is null
.
Die Implementierung von comparison
hat einen Fehler während der Sortierung verursacht.The implementation of comparison
caused an error during the sort. Beispielsweise gibt comparison
beim Vergleichen eines Elements mit sich selbst möglicherweise nicht 0 zurück.For example, comparison
might not return 0 when comparing an item with itself.
Beispiele
Der folgende Code veranschaulicht die Sort-und Sort-Methoden Überladungen für ein einfaches Geschäftsobjekt.The following code demonstrates the Sort and Sort method overloads on a simple business object. Wenn Sie die Sort-Methode aufrufen, wird der Standardcomparer für den Teiltyp verwendet, und die Sort-Methode wird mit einer anonymen Methode implementiert.Calling the Sort method results in the use of the default comparer for the Part type, and the Sort method is implemented using an anonymous method.
using System;
using 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 : IEquatable<Part> , IComparable<Part>
{
public string PartName { get; set; }
public int PartId { get; set; }
public override string ToString()
{
return "ID: " + PartId + " Name: " + PartName;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Part objAsPart = obj as Part;
if (objAsPart == null) return false;
else return Equals(objAsPart);
}
public int SortByNameAscending(string name1, string name2)
{
return name1.CompareTo(name2);
}
// Default comparer for Part type.
public int CompareTo(Part comparePart)
{
// A null value means that this object is greater.
if (comparePart == null)
return 1;
else
return this.PartId.CompareTo(comparePart.PartId);
}
public override int GetHashCode()
{
return PartId;
}
public bool Equals(Part other)
{
if (other == null) return false;
return (this.PartId.Equals(other.PartId));
}
// Should also override == and != operators.
}
public class Example
{
public static void Main()
{
// Create a list of parts.
List<Part> parts = new List<Part>();
// Add parts to the list.
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName= "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;
// Name intentionally left null.
parts.Add(new Part() { PartId = 1334 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
// Write out the parts in the list. This will call the overridden
// ToString method in the Part class.
Console.WriteLine("\nBefore sort:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// Call Sort on the list. This will use the
// default comparer, which is the Compare method
// implemented on Part.
parts.Sort();
Console.WriteLine("\nAfter sort by part number:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// This shows calling the Sort(Comparison(T) overload using
// an anonymous method for the Comparison delegate.
// This method treats null as the lesser of two values.
parts.Sort(delegate(Part x, Part y)
{
if (x.PartName == null && y.PartName == null) return 0;
else if (x.PartName == null) return -1;
else if (y.PartName == null) return 1;
else return x.PartName.CompareTo(y.PartName);
});
Console.WriteLine("\nAfter sort by name:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
/*
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
*/
}
}
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
Im folgenden Beispiel wird die Sort(Comparison<T>)-Methoden Überladung veranschaulicht.The following example demonstrates the Sort(Comparison<T>) method overload.
Das Beispiel definiert eine Alternative Vergleichsmethode für Zeichen folgen mit dem Namen CompareDinosByLength
.The example defines an alternative comparison method for strings, named CompareDinosByLength
. Diese Methode funktioniert wie folgt: zuerst werden die Vergleiche auf null
getestet, und ein NULL-Verweis wird als kleiner als ein nicht-NULL-Wert behandelt.This method works as follows: First, the comparands are tested for null
, and a null reference is treated as less than a non-null. Zweitens werden die Zeichen folgen Längen verglichen, und die längere Zeichenfolge wird als größer eingestuft.Second, the string lengths are compared, and the longer string is deemed to be greater. Drittens: Wenn die Längen gleich sind, wird der normale Zeichen folgen Vergleich verwendet.Third, if the lengths are equal, ordinary string comparison is used.
Eine List<T> von Zeichen folgen wird erstellt und mit vier Zeichen folgen ohne bestimmte Reihenfolge aufgefüllt.A List<T> of strings is created and populated with four strings, in no particular order. Die Liste enthält auch eine leere Zeichenfolge und einen NULL-Verweis.The list also includes an empty string and a null reference. Die Liste wird angezeigt, mithilfe eines Comparison<T> generischen Delegaten sortiert, der die CompareDinosByLength
-Methode darstellt, und wird erneut angezeigt.The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength
method, and displayed again.
using namespace System;
using namespace System::Collections::Generic;
int CompareDinosByLength(String^ x, String^ y)
{
if (x == nullptr)
{
if (y == nullptr)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == nullptr)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x->Length.CompareTo(y->Length);
if (retval != 0)
{
// 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);
}
}
}
};
void Display(List<String^>^ list)
{
Console::WriteLine();
for each(String^ s in list)
{
if (s == nullptr)
Console::WriteLine("(null)");
else
Console::WriteLine("\"{0}\"", s);
}
};
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Pachycephalosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("");
dinosaurs->Add(nullptr);
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
Display(dinosaurs);
Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
dinosaurs->Sort(
gcnew Comparison<String^>(CompareDinosByLength));
Display(dinosaurs);
}
/* This code example produces the following output:
"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"
Sort with generic Comparison<String^> delegate:
(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
*/
using System;
using System.Collections.Generic;
public class Example
{
private static int CompareDinosByLength(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x.Length.CompareTo(y.Length);
if (retval != 0)
{
// 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);
}
}
}
}
public static void Main()
{
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("");
dinosaurs.Add(null);
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
Display(dinosaurs);
Console.WriteLine("\nSort with generic Comparison<string> delegate:");
dinosaurs.Sort(CompareDinosByLength);
Display(dinosaurs);
}
private static void Display(List<string> list)
{
Console.WriteLine();
foreach( string s in list )
{
if (s == null)
Console.WriteLine("(null)");
else
Console.WriteLine("\"{0}\"", s);
}
}
}
/* This code example produces the following output:
"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"
Sort with generic Comparison<string> delegate:
(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
*/
Imports System.Collections.Generic
Public Class Example
Private Shared Function CompareDinosByLength( _
ByVal x As String, ByVal y As String) As Integer
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
Public Shared Sub Main()
Dim dinosaurs As New List(Of String)
dinosaurs.Add("Pachycephalosaurus")
dinosaurs.Add("Amargasaurus")
dinosaurs.Add("")
dinosaurs.Add(Nothing)
dinosaurs.Add("Mamenchisaurus")
dinosaurs.Add("Deinonychus")
Display(dinosaurs)
Console.WriteLine(vbLf & "Sort with generic Comparison(Of String) delegate:")
dinosaurs.Sort(AddressOf CompareDinosByLength)
Display(dinosaurs)
End Sub
Private Shared Sub Display(ByVal lis As List(Of String))
Console.WriteLine()
For Each s As String In lis
If s Is Nothing Then
Console.WriteLine("(Nothing)")
Else
Console.WriteLine("""{0}""", s)
End If
Next
End Sub
End Class
' This code example produces the following output:
'
'"Pachycephalosaurus"
'"Amargasaurus"
'""
'(Nothing)
'"Mamenchisaurus"
'"Deinonychus"
'
'Sort with generic Comparison(Of String) delegate:
'
'(Nothing)
'""
'"Deinonychus"
'"Amargasaurus"
'"Mamenchisaurus"
'"Pachycephalosaurus"
Hinweise
Wenn comparison
bereitgestellt wird, werden die Elemente der List<T> mithilfe der Methode sortiert, die durch den-Delegaten dargestellt wird.If comparison
is provided, the elements of the List<T> are sorted using the method represented by the delegate.
Wenn comparison
null
ist, wird ein ArgumentNullException ausgelöst.If comparison
is null
, an ArgumentNullException is thrown.
Diese Methode verwendet Array.Sort, das die Introspektion wie folgt anwendet:This method uses Array.Sort, which applies the introspective sort as follows:
Wenn die Partitionsgröße kleiner als oder gleich 16 Elementen ist, wird ein Einfügungs Algorithmus verwendet.If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm
Wenn die Anzahl der Partitionen 2 Protokoll nüberschreitet, wobei n der Bereich des Eingabe Arrays ist, wird ein Heapsort -Algorithmus verwendet.If the number of partitions exceeds 2 log n, where n is the range of the input array, it uses a Heapsort algorithm.
Andernfalls wird ein QuickSort-Algorithmus verwendet.Otherwise, it uses a Quicksort algorithm.
Diese Implementierung führt eine instabile Sortierung aus. Das heißt, wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge der Elemente bei, die gleich sind.In contrast, a stable sort preserves the order of elements that are equal.
Im Durchschnitt ist diese Methode ein O (n log n)-Vorgang, bei dem n Countist. im schlimmsten Fall ist dies ein O (n2)-Vorgang.On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n2) operation.
Siehe auch
Sort(Int32, Int32, IComparer<T>)
Sortiert die Elemente in einem Bereich von Elementen in der List<T> mithilfe des angegebenen Vergleichs.Sorts the elements in a range of elements in List<T> using the specified comparer.
public:
void Sort(int index, int count, System::Collections::Generic::IComparer<T> ^ comparer);
public void Sort (int index, int count, System.Collections.Generic.IComparer<T> comparer);
member this.Sort : int * int * System.Collections.Generic.IComparer<'T> -> unit
Public Sub Sort (index As Integer, count As Integer, comparer As IComparer(Of T))
Parameter
- index
- Int32
Der nullbasierte Startindex des zu sortierenden Bereichs.The zero-based starting index of the range to sort.
- count
- Int32
Die Länge des zu sortierenden Bereichs.The length of the range to sort.
- comparer
- IComparer<T>
Die IComparer<T>-Implementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null
, wenn der Standardvergleich Default verwendet werden soll.The IComparer<T> implementation to use when comparing elements, or null
to use the default comparer Default.
Ausnahmen
index
ist kleiner als 0.index
is less than 0.
- oder --or-
count
ist kleiner als 0.count
is less than 0.
index
und count
geben keinen gültigen Bereich in der List<T> an.index
and count
do not specify a valid range in the List<T>.
- oder --or-
Die Implementierung von comparer
hat einen Fehler während der Sortierung verursacht.The implementation of comparer
caused an error during the sort. comparer
kann z. B. möglicherweise nicht 0 zurückgeben, wenn ein Element mit sich selbst verglichen wird.For example, comparer
might not return 0 when comparing an item with itself.
comparer
ist null
, und der Standardcomparer Default kann die Implementierung der generischen IComparable<T>-Schnittstelle oder der IComparable-Schnittstelle für den Typ T
nicht finden.comparer
is null
, and the default comparer Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T
.
Beispiele
Im folgenden Beispiel werden die Sort(Int32, Int32, IComparer<T>)-Methoden Überladung und die BinarySearch(Int32, Int32, T, IComparer<T>)-Methoden Überladung veranschaulicht.The following example demonstrates the Sort(Int32, Int32, IComparer<T>) method overload and the BinarySearch(Int32, Int32, T, IComparer<T>) method overload.
Im Beispiel wird ein alternativer Vergleich für Zeichen folgen mit dem Namen DinoCompare definiert, der den IComparer<string>
(IComparer(Of String)
in Visual Basic, IComparer<String^>
C++in Visual) generischen Schnittstelle implementiert.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. Der Vergleich funktioniert wie folgt: zuerst werden die Vergleiche auf null
getestet, und ein NULL-Verweis wird als kleiner als ein nicht-NULL-Wert behandelt.The comparer works as follows: First, the comparands are tested for null
, and a null reference is treated as less than a non-null. Zweitens werden die Zeichen folgen Längen verglichen, und die längere Zeichenfolge wird als größer eingestuft.Second, the string lengths are compared, and the longer string is deemed to be greater. Drittens: Wenn die Längen gleich sind, wird der normale Zeichen folgen Vergleich verwendet.Third, if the lengths are equal, ordinary string comparison is used.
Eine List<T> von Zeichen folgen wird erstellt und mit den Namen von fünf herbialous-dinosaern und drei karnevaliösen dinosaern aufgefüllt.A List<T> of strings is created and populated with the names of five herbivorous dinosaurs and three carnivorous dinosaurs. Innerhalb der beiden Gruppen befinden sich die Namen nicht in einer bestimmten Sortierreihenfolge.Within each of the two groups, the names are not in any particular sort order. Die Liste wird angezeigt, der Bereich der HERBIVORES wird mit dem alternativen Comparer sortiert, und die Liste wird erneut angezeigt.The list is displayed, the range of herbivores is sorted using the alternate comparer, and the list is displayed again.
Die BinarySearch(Int32, Int32, T, IComparer<T>)-Methoden Überladung wird dann verwendet, um nur den Bereich von HERBIVORES für "Brachiosaurus" zu durchsuchen.The BinarySearch(Int32, Int32, T, IComparer<T>) method overload is then used to search only the range of herbivores for "Brachiosaurus". Die Zeichenfolge wurde nicht gefunden, und das bitweise Komplement (der ~- C# Operator in C++und Visual, Xor
-1 in Visual Basic) der negativen Zahl, die von der BinarySearch(Int32, Int32, T, IComparer<T>)-Methode zurückgegeben wird, wird als Index zum Einfügen der neuen Zeichenfolge verwendet.The string is not found, and the bitwise complement (the ~ operator in C# and Visual C++, Xor
-1 in Visual Basic) of the negative number returned by the BinarySearch(Int32, Int32, T, IComparer<T>) method is used as an index for inserting the new string.
using namespace System;
using namespace System::Collections::Generic;
public ref class DinoComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
if (x == nullptr)
{
if (y == nullptr)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == nullptr)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x->Length.CompareTo(y->Length);
if (retval != 0)
{
// 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);
}
}
}
}
};
void Display(List<String^>^ list)
{
Console::WriteLine();
for each(String^ s in list)
{
Console::WriteLine(s);
}
};
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Pachycephalosaurus");
dinosaurs->Add("Parasauralophus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Galimimus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
dinosaurs->Add("Oviraptor");
dinosaurs->Add("Tyrannosaurus");
int herbivores = 5;
Display(dinosaurs);
DinoComparer^ dc = gcnew DinoComparer();
Console::WriteLine("\nSort a range with the alternate comparer:");
dinosaurs->Sort(0, herbivores, dc);
Display(dinosaurs);
Console::WriteLine("\nBinarySearch a range and Insert \"{0}\":",
"Brachiosaurus");
int index = dinosaurs->BinarySearch(0, herbivores, "Brachiosaurus", dc);
if (index < 0)
{
dinosaurs->Insert(~index, "Brachiosaurus");
herbivores++;
}
Display(dinosaurs);
}
/* This code example produces the following output:
Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus
Sort a range with the alternate comparer:
Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
BinarySearch a range and Insert "Brachiosaurus":
Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
*/
using System;
using System.Collections.Generic;
public class DinoComparer: IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x.Length.CompareTo(y.Length);
if (retval != 0)
{
// 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);
}
}
}
}
}
public class Example
{
public static void Main()
{
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Parasauralophus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Galimimus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Tyrannosaurus");
int herbivores = 5;
Display(dinosaurs);
DinoComparer dc = new DinoComparer();
Console.WriteLine("\nSort a range with the alternate comparer:");
dinosaurs.Sort(0, herbivores, dc);
Display(dinosaurs);
Console.WriteLine("\nBinarySearch a range and Insert \"{0}\":",
"Brachiosaurus");
int index = dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc);
if (index < 0)
{
dinosaurs.Insert(~index, "Brachiosaurus");
herbivores++;
}
Display(dinosaurs);
}
private static void Display(List<string> list)
{
Console.WriteLine();
foreach( string s in list )
{
Console.WriteLine(s);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus
Sort a range with the alternate comparer:
Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
BinarySearch a range and Insert "Brachiosaurus":
Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
*/
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("Parasauralophus")
dinosaurs.Add("Amargasaurus")
dinosaurs.Add("Galimimus")
dinosaurs.Add("Mamenchisaurus")
dinosaurs.Add("Deinonychus")
dinosaurs.Add("Oviraptor")
dinosaurs.Add("Tyrannosaurus")
Dim herbivores As Integer = 5
Display(dinosaurs)
Dim dc As New DinoComparer
Console.WriteLine(vbLf & _
"Sort a range with the alternate comparer:")
dinosaurs.Sort(0, herbivores, dc)
Display(dinosaurs)
Console.WriteLine(vbLf & _
"BinarySearch a range and Insert ""{0}"":", _
"Brachiosaurus")
Dim index As Integer = _
dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc)
If index < 0 Then
index = index Xor -1
dinosaurs.Insert(index, "Brachiosaurus")
herbivores += 1
End If
Display(dinosaurs)
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
'Parasauralophus
'Amargasaurus
'Galimimus
'Mamenchisaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'Sort a range with the alternate comparer:
'
'Galimimus
'Amargasaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'BinarySearch a range and Insert "Brachiosaurus":
'
'Galimimus
'Amargasaurus
'Brachiosaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
Hinweise
Wenn comparer
bereitgestellt wird, werden die Elemente der List<T> mithilfe der angegebenen IComparer<T>-Implementierung sortiert.If comparer
is provided, the elements of the List<T> are sorted using the specified IComparer<T> implementation.
Wenn comparer
null
ist, überprüft der Standardcomparer Comparer<T>.Default, ob der Typ T
die IComparable<T> generische Schnittstelle implementiert, und verwendet diese Implementierung, falls verfügbar.If comparer
is null
, the default comparer Comparer<T>.Default checks whether type T
implements the IComparable<T> generic interface and uses that implementation, if available. Andernfalls Comparer<T>.Default überprüft, ob der Typ T
die IComparable-Schnittstelle implementiert.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Wenn Type T
keine Schnittstelle implementiert, löst Comparer<T>.Default eine InvalidOperationExceptionaus.If type T
does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.
Diese Methode verwendet Array.Sort, das die Introspektion wie folgt anwendet:This method uses Array.Sort, which applies the introspective sort as follows:
Wenn die Partitionsgröße kleiner als oder gleich 16 Elementen ist, wird ein Einfügungs Algorithmus verwendet.If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm
Wenn die Anzahl der Partitionen 2 Protokoll nüberschreitet, wobei n der Bereich des Eingabe Arrays ist, wird ein Heapsort -Algorithmus verwendet.If the number of partitions exceeds 2 log n, where n is the range of the input array, it uses a Heapsort algorithm.
Andernfalls wird ein QuickSort-Algorithmus verwendet.Otherwise, it uses a Quicksort algorithm.
Diese Implementierung führt eine instabile Sortierung aus. Das heißt, wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge der Elemente bei, die gleich sind.In contrast, a stable sort preserves the order of elements that are equal.
Im Durchschnitt ist diese Methode ein O (n log n)-Vorgang, bei dem n Countist. im schlimmsten Fall ist dies ein O (n2)-Vorgang.On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n2) operation.
Siehe auch
Sort()
Sortiert die Elemente in der gesamten List<T> mithilfe des Standardcomparers.Sorts the elements in the entire List<T> using the default comparer.
public:
void Sort();
public void Sort ();
member this.Sort : unit -> unit
Public Sub Sort ()
Ausnahmen
Der Standardcomparer Default kann keine Implementierung der generischen IComparable<T>-Schnittstelle oder der IComparable-Schnittstelle für den Typ T
finden.The default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T
.
Beispiele
Hinweis
Einige der C#-Beispiele in diesem Artikel werden in der Inlinecodeausführung und dem Playground von Try.NET ausgeführt.Some of the C# examples in this article run in the Try.NET inline code runner and playground. Wenn vorhanden, klicken Sie auf die Schaltfläche Ausführen, um ein Beispiel in einem interaktiven Fenster auszuführen.When present, select the Run button to run an example in an interactive window. Nachdem Sie den Code ausgeführt haben, können Sie ihn ändern und den geänderten Code durch erneutes Anklicken der Schaltfläche Ausführen ausführen.Once you execute the code, you can modify it and run the modified code by selecting Run again. Der geänderte Code wird entweder im interaktiven Fenster ausgeführt, oder das interaktive Fenster zeigt alle C#-Compilerfehlermeldungen an, wenn die Kompilierung fehlschlägt.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
Im folgenden Beispiel werden einige Namen zu einem List<String>
Objekt hinzugefügt. die Liste wird in der unsortierten Reihenfolge angezeigt, die Sort-Methode wird aufgerufen, und anschließend wird die sortierte Liste angezeigt.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.
String[] names = { "Samuel", "Dakota", "Koani", "Saya", "Vanya", "Jody",
"Yiska", "Yuma", "Jody", "Nikita" };
var nameList = new List<String>();
nameList.AddRange(names);
Console.WriteLine("List in unsorted order: ");
foreach (var name in nameList)
Console.Write(" {0}", name);
Console.WriteLine(Environment.NewLine);
nameList.Sort();
Console.WriteLine("List in sorted order: ");
foreach (var name in nameList)
Console.Write(" {0}", name);
Console.WriteLine();
// The example displays the following output:
// List in unsorted order:
// Samuel Dakota Koani Saya Vanya Jody Yiska Yuma Jody Nikita
//
// List in sorted order:
// Dakota Jody Jody Koani Nikita Samuel Saya Vanya Yiska Yuma
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim names() As String = { "Samuel", "Dakota", "Koani", "Saya",
"Vanya", "Jody", "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 Jody Yiska Yuma Jody Nikita
'
' List in sorted order:
' Dakota Jody Jody Koani Nikita Samuel Saya Vanya Yiska Yuma
Der folgende Code veranschaulicht die Sort()-und Sort(Comparison<T>)-Methoden Überladungen für ein einfaches Geschäftsobjekt.The following code demonstrates the Sort() and Sort(Comparison<T>) method overloads on a simple business object. Wenn Sie die Sort()-Methode aufrufen, wird der Standardcomparer für den Teiltyp verwendet, und die Sort(Comparison<T>)-Methode wird mit einer anonymen Methode implementiert.Calling the Sort() method results in the use of the default comparer for the Part type, and the Sort(Comparison<T>) method is implemented by using an anonymous method.
using System;
using 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 : IEquatable<Part> , IComparable<Part>
{
public string PartName { get; set; }
public int PartId { get; set; }
public override string ToString()
{
return "ID: " + PartId + " Name: " + PartName;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Part objAsPart = obj as Part;
if (objAsPart == null) return false;
else return Equals(objAsPart);
}
public int SortByNameAscending(string name1, string name2)
{
return name1.CompareTo(name2);
}
// Default comparer for Part type.
public int CompareTo(Part comparePart)
{
// A null value means that this object is greater.
if (comparePart == null)
return 1;
else
return this.PartId.CompareTo(comparePart.PartId);
}
public override int GetHashCode()
{
return PartId;
}
public bool Equals(Part other)
{
if (other == null) return false;
return (this.PartId.Equals(other.PartId));
}
// Should also override == and != operators.
}
public class Example
{
public static void Main()
{
// Create a list of parts.
List<Part> parts = new List<Part>();
// Add parts to the list.
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName= "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;
// Name intentionally left null.
parts.Add(new Part() { PartId = 1334 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
// Write out the parts in the list. This will call the overridden
// ToString method in the Part class.
Console.WriteLine("\nBefore sort:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// Call Sort on the list. This will use the
// default comparer, which is the Compare method
// implemented on Part.
parts.Sort();
Console.WriteLine("\nAfter sort by part number:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// This shows calling the Sort(Comparison(T) overload using
// an anonymous method for the Comparison delegate.
// This method treats null as the lesser of two values.
parts.Sort(delegate(Part x, Part y)
{
if (x.PartName == null && y.PartName == null) return 0;
else if (x.PartName == null) return -1;
else if (y.PartName == null) return 1;
else return x.PartName.CompareTo(y.PartName);
});
Console.WriteLine("\nAfter sort by name:");
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
/*
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
*/
}
}
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
Im folgenden Beispiel werden die Sort()-Methoden Überladung und die BinarySearch(T)-Methoden Überladung veranschaulicht.The following example demonstrates the Sort() method overload and the BinarySearch(T) method overload. Eine List<T> von Zeichen folgen wird erstellt und mit vier Zeichen folgen ohne bestimmte Reihenfolge aufgefüllt.A List<T> of strings is created and populated with four strings, in no particular order. Die Liste wird angezeigt, sortiert und erneut angezeigt.The list is displayed, sorted, and displayed again.
Die BinarySearch(T)-Methoden Überladung wird dann verwendet, um nach zwei Zeichen folgen zu suchen, die nicht in der Liste enthalten sind, und die Insert-Methode wird verwendet, um Sie einzufügen.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. Der Rückgabewert der BinarySearch-Methode ist in jedem Fall negativ, da die Zeichen folgen nicht in der Liste enthalten sind.The return value of the BinarySearch method is negative in each case, because the strings are not in the list. Das bitweise Komplement (der ~-Operator in C# und Visual C++, Xor
-1 in Visual Basic) dieser negativen Zahl erzeugt den Index des ersten Elements in der Liste, das größer als die Such Zeichenfolge ist, und das Einfügen an dieser Stelle behält die Sortierreihenfolge bei.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. Die zweite Such Zeichenfolge ist größer als jedes Element in der Liste, sodass sich die Einfügeposition am Ende der Liste befindet.The second search string is larger than any element in the list, so the insertion position is at the end of the list.
using namespace System;
using namespace System::Collections::Generic;
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Pachycephalosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nSort");
dinosaurs->Sort();
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
int index = dinosaurs->BinarySearch("Coelophysis");
if (index < 0)
{
dinosaurs->Insert(~index, "Coelophysis");
}
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
index = dinosaurs->BinarySearch("Tyrannosaurus");
if (index < 0)
{
dinosaurs->Insert(~index, "Tyrannosaurus");
}
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
}
/* 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
*/
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Initial list:");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nSort:");
dinosaurs.Sort();
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
int index = dinosaurs.BinarySearch("Coelophysis");
if (index < 0)
{
dinosaurs.Insert(~index, "Coelophysis");
}
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
index = dinosaurs.BinarySearch("Tyrannosaurus");
if (index < 0)
{
dinosaurs.Insert(~index, "Tyrannosaurus");
}
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
/* This code example produces the following output:
Initial list:
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
*/
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
Hinweise
Diese Methode verwendet den Standardcomparer-Comparer<T>.Default für den Typ T
, um die Reihenfolge der Listenelemente zu bestimmen.This method uses the default comparer Comparer<T>.Default for type T
to determine the order of list elements. Die Comparer<T>.Default-Eigenschaft überprüft, ob der Typ T
die IComparable<T> generische Schnittstelle implementiert, und verwendet diese Implementierung, falls verfügbar.The Comparer<T>.Default property checks whether type T
implements the IComparable<T> generic interface and uses that implementation, if available. Andernfalls Comparer<T>.Default überprüft, ob der Typ T
die IComparable-Schnittstelle implementiert.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Wenn Type T
keine Schnittstelle implementiert, löst Comparer<T>.Default eine InvalidOperationExceptionaus.If type T
does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.
Diese Methode verwendet die Array.Sort-Methode, die die Introspektion wie folgt anwendet:This method uses the Array.Sort method, which applies the introspective sort as follows:
Wenn die Partitionsgröße kleiner als oder gleich 16 Elementen ist, wird ein Einfügungs Algorithmus verwendet.If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.
Wenn die Anzahl der Partitionen 2 Protokoll nüberschreitet, wobei n der Bereich des Eingabe Arrays ist, wird ein Heapsort-Algorithmus verwendet.If the number of partitions exceeds 2 log n, where n is the range of the input array, it uses a Heapsort algorithm.
Andernfalls wird ein QuickSort-Algorithmus verwendet.Otherwise, it uses a Quicksort algorithm.
Diese Implementierung führt eine instabile Sortierung aus. Das heißt, wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge der Elemente bei, die gleich sind.In contrast, a stable sort preserves the order of elements that are equal.
Im Durchschnitt ist diese Methode ein O (n log n)-Vorgang, bei dem n Countist. im schlimmsten Fall ist dies ein O (n2)-Vorgang.On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n2) operation.
Siehe auch
Sort(IComparer<T>)
Sortiert die Elemente in der gesamten List<T> mithilfe des angegebenen Comparers.Sorts the elements in the entire List<T> using the specified comparer.
public:
void Sort(System::Collections::Generic::IComparer<T> ^ comparer);
public void Sort (System.Collections.Generic.IComparer<T> comparer);
member this.Sort : System.Collections.Generic.IComparer<'T> -> unit
Public Sub Sort (comparer As IComparer(Of T))
Parameter
- comparer
- IComparer<T>
Die IComparer<T>-Implementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null
, wenn der Standardvergleich Default verwendet werden soll.The IComparer<T> implementation to use when comparing elements, or null
to use the default comparer Default.
Ausnahmen
comparer
ist null
, und der Standardcomparer Default kann die Implementierung der generischen IComparable<T>-Schnittstelle oder der IComparable-Schnittstelle für den Typ T
nicht finden.comparer
is null
, and the default comparer Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T
.
Die Implementierung von comparer
hat während der Sortierung einen Fehler verursacht.The implementation of comparer
caused an error during the sort. Beispielsweise gibt comparer
beim Vergleichen eines Elements mit sich selbst möglicherweise nicht 0 zurück.For example, comparer
might not return 0 when comparing an item with itself.
Beispiele
Im folgenden Beispiel werden die Sort(IComparer<T>)-Methoden Überladung und die BinarySearch(T, IComparer<T>)-Methoden Überladung veranschaulicht.The following example demonstrates the Sort(IComparer<T>) method overload and the BinarySearch(T, IComparer<T>) method overload.
Im Beispiel wird ein alternativer Vergleich für Zeichen folgen mit dem Namen DinoCompare definiert, der den IComparer<string>
(IComparer(Of String)
in Visual Basic, IComparer<String^>
C++in Visual) generischen Schnittstelle implementiert.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. Der Vergleich funktioniert wie folgt: zuerst werden die Vergleiche auf null
getestet, und ein NULL-Verweis wird als kleiner als ein nicht-NULL-Wert behandelt.The comparer works as follows: First, the comparands are tested for null
, and a null reference is treated as less than a non-null. Zweitens werden die Zeichen folgen Längen verglichen, und die längere Zeichenfolge wird als größer eingestuft.Second, the string lengths are compared, and the longer string is deemed to be greater. Drittens: Wenn die Längen gleich sind, wird der normale Zeichen folgen Vergleich verwendet.Third, if the lengths are equal, ordinary string comparison is used.
Eine List<T> von Zeichen folgen wird erstellt und mit vier Zeichen folgen ohne bestimmte Reihenfolge aufgefüllt.A List<T> of strings is created and populated with four strings, in no particular order. Die Liste wird angezeigt, mit dem alternativen Vergleich sortiert und erneut angezeigt.The list is displayed, sorted using the alternate comparer, and displayed again.
Die BinarySearch(T, IComparer<T>)-Methoden Überladung wird dann verwendet, um nach mehreren Zeichen folgen zu suchen, die nicht in der Liste enthalten sind, wobei der Alternative Vergleich verwendet wird.The BinarySearch(T, IComparer<T>) method overload is then used to search for several strings that are not in the list, employing the alternate comparer. Die Insert-Methode wird zum Einfügen der Zeichen folgen verwendet.The Insert method is used to insert the strings. Diese beiden Methoden befinden sich in der Funktion mit dem Namen SearchAndInsert
, zusammen mit dem Code, um das bitweise Komplement (der C# ~- C++Operator in und Visual, Xor
-1 in Visual Basic) der von BinarySearch(T, IComparer<T>) zurückgegebenen negativen Zahl zu verwenden und Sie als Index für das Einfügen der neuen Zeichenfolge zu verwenden.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<T>) and use it as an index for inserting the new string.
using namespace System;
using namespace System::Collections::Generic;
public ref class DinoComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
if (x == nullptr)
{
if (y == nullptr)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == nullptr)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x->Length.CompareTo(y->Length);
if (retval != 0)
{
// 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);
}
}
}
}
};
void SearchAndInsert(List<String^>^ list, String^ insert,
DinoComparer^ dc)
{
Console::WriteLine("\nBinarySearch and Insert \"{0}\":", insert);
int index = list->BinarySearch(insert, dc);
if (index < 0)
{
list->Insert(~index, insert);
}
};
void Display(List<String^>^ list)
{
Console::WriteLine();
for each(String^ s in list)
{
Console::WriteLine(s);
}
};
void main()
{
List<String^>^ dinosaurs = gcnew List<String^>();
dinosaurs->Add("Pachycephalosaurus");
dinosaurs->Add("Amargasaurus");
dinosaurs->Add("Mamenchisaurus");
dinosaurs->Add("Deinonychus");
Display(dinosaurs);
DinoComparer^ dc = gcnew DinoComparer();
Console::WriteLine("\nSort 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, nullptr, dc);
Display(dinosaurs);
}
/* 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
*/
using System;
using System.Collections.Generic;
public class DinoComparer: IComparer<string>
{
public int Compare(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x.Length.CompareTo(y.Length);
if (retval != 0)
{
// 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);
}
}
}
}
}
public class Example
{
public static void Main()
{
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
Display(dinosaurs);
DinoComparer dc = new DinoComparer();
Console.WriteLine("\nSort 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, null, dc);
Display(dinosaurs);
}
private static void SearchAndInsert(List<string> list,
string insert, DinoComparer dc)
{
Console.WriteLine("\nBinarySearch and Insert \"{0}\":", insert);
int index = list.BinarySearch(insert, dc);
if (index < 0)
{
list.Insert(~index, insert);
}
}
private static void Display(List<string> list)
{
Console.WriteLine();
foreach( string s in list )
{
Console.WriteLine(s);
}
}
}
/* 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
*/
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
Hinweise
Wenn comparer
bereitgestellt wird, werden die Elemente der List<T> mithilfe der angegebenen IComparer<T>-Implementierung sortiert.If comparer
is provided, the elements of the List<T> are sorted using the specified IComparer<T> implementation.
Wenn comparer
null
ist, überprüft der Standardcomparer Comparer<T>.Default, ob der Typ T
die IComparable<T> generische Schnittstelle implementiert, und verwendet diese Implementierung, falls verfügbar.If comparer
is null
, the default comparer Comparer<T>.Default checks whether type T
implements the IComparable<T> generic interface and uses that implementation, if available. Andernfalls Comparer<T>.Default überprüft, ob der Typ T
die IComparable-Schnittstelle implementiert.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Wenn Type T
keine Schnittstelle implementiert, löst Comparer<T>.Default eine InvalidOperationExceptionaus.If type T
does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.
Diese Methode verwendet die Array.Sort-Methode, die die Introspektion wie folgt anwendet:This method uses the Array.Sort method, which applies the introspective sort as follows:
Wenn die Partitionsgröße kleiner als oder gleich 16 Elementen ist, wird ein Einfügungs Algorithmus verwendet.If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.
Wenn die Anzahl der Partitionen 2 Protokoll nüberschreitet, wobei n der Bereich des Eingabe Arrays ist, wird ein Heapsort-Algorithmus verwendet.If the number of partitions exceeds 2 log n, where n is the range of the input array, it uses a Heapsort algorithm.
Andernfalls wird ein QuickSort-Algorithmus verwendet.Otherwise, it uses a Quicksort algorithm.
Diese Implementierung führt eine instabile Sortierung aus. Das heißt, wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge der Elemente bei, die gleich sind.In contrast, a stable sort preserves the order of elements that are equal.
Im Durchschnitt ist diese Methode ein O (n log n)-Vorgang, bei dem n Countist. im schlimmsten Fall ist dies ein O (n2)-Vorgang.On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n2) operation.