List<T>.Sort Metoda

Definicja

Sortuje elementy lub część elementów w obiekcie List<T> przy użyciu określonej lub domyślnej IComparer<T> implementacji albo dostarczonego Comparison<T> delegata, aby porównać elementy listy.

Przeciążenia

Sort(Comparison<T>)

Sortuje elementy w całości List<T> przy użyciu określonego Comparison<T>elementu .

Sort(Int32, Int32, IComparer<T>)

Sortuje elementy w zakresie elementów przy List<T> użyciu określonego modułu porównującego.

Sort()

Sortuje elementy w całości List<T> przy użyciu domyślnego modułu porównującego.

Sort(IComparer<T>)

Sortuje elementy w całości List<T> przy użyciu określonego modułu porównującego.

Sort(Comparison<T>)

Źródło:
List.cs
Źródło:
List.cs
Źródło:
List.cs

Sortuje elementy w całości List<T> przy użyciu określonego Comparison<T>elementu .

C#
public void Sort (Comparison<T> comparison);

Parametry

comparison
Comparison<T>

Element Comparison<T> do użycia podczas porównywania elementów.

Wyjątki

comparison to null.

Implementacja spowodowała comparison błąd podczas sortowania. Na przykład comparison może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

Przykłady

Poniższy kod demonstruje Sort przeciążenia metody i Sort dla prostego obiektu biznesowego. Sort Wywołanie metody powoduje użycie domyślnego porównania dla typu części, a Sort metoda jest implementowana przy użyciu metody anonimowej.

C#
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

         */
    }
}

W poniższym przykładzie pokazano Sort(Comparison<T>) przeciążenie metody.

W przykładzie zdefiniowano alternatywną metodę porównania ciągów o nazwie CompareDinosByLength. Ta metoda działa w następujący sposób: Najpierw comparands są testowane pod kątem null, a odwołanie o wartości null jest traktowane jako mniejsze niż wartość innej niż null. Po drugie, długości ciągów są porównywane, a dłuższy ciąg jest uznawany za większy. Po trzecie, jeśli długości są równe, używane jest zwykłe porównanie ciągów.

Ciągi List<T> są tworzone i wypełniane czterema ciągami, bez określonej kolejności. Lista zawiera również pusty ciąg i odwołanie o wartości null. Zostanie wyświetlona lista posortowana przy użyciu delegata ogólnego reprezentującego Comparison<T> metodę i wyświetlona CompareDinosByLength ponownie.

C#
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"
 */

Uwagi

Jeśli comparison zostanie podana wartość , elementy List<T> są sortowane przy użyciu metody reprezentowanej przez delegata.

Jeśli comparison parametr ma nullwartość , ArgumentNullException element jest zgłaszany.

Ta metoda używa Array.Sortklasy , która stosuje sortowanie introspektywne w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania

  • Jeśli liczba partycji przekracza 2 dziennik n, gdzie n jest zakresem tablicy wejściowej, używa algorytmu Heapsort .

  • W przeciwnym razie używa algorytmu Quicksort.

Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n to Count.

Zobacz też

Dotyczy

.NET 9 i inne wersje
Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort(Int32, Int32, IComparer<T>)

Źródło:
List.cs
Źródło:
List.cs
Źródło:
List.cs

Sortuje elementy w zakresie elementów przy List<T> użyciu określonego modułu porównującego.

C#
public void Sort (int index, int count, System.Collections.Generic.IComparer<T> comparer);
C#
public void Sort (int index, int count, System.Collections.Generic.IComparer<T>? comparer);

Parametry

index
Int32

Indeks początkowy od zera zakresu do sortowania.

count
Int32

Długość zakresu do sortowania.

comparer
IComparer<T>

Implementacja IComparer<T> używana podczas porównywania elementów lub null używania domyślnego modułu Defaultporównującego .

Wyjątki

index wartość jest mniejsza niż 0.

-lub-

count wartość jest mniejsza niż 0.

index i count nie należy określać prawidłowego zakresu w obiekcie List<T>.

-lub-

Implementacja spowodowała comparer błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a domyślny moduł porównujący Default nie może odnaleźć implementacji interfejsu IComparable<T> ogólnego lub interfejsu IComparable dla typu T.

Przykłady

W poniższym przykładzie pokazano Sort(Int32, Int32, IComparer<T>) przeciążenie metody i BinarySearch(Int32, Int32, T, IComparer<T>) przeciążenie metody.

W przykładzie zdefiniowano alternatywny moduł porównujący ciągów o nazwie DinoCompare, który implementuje IComparer<string> interfejs ogólny (IComparer(Of String) w języku Visual Basic IComparer<String^> w języku Visual C++). Narzędzie porównujące działa w następujący sposób: najpierw współzależność jest testowana pod kątem nullwartości , a odwołanie o wartości null jest traktowane jako mniejsze niż niepuste. Po drugie, długości ciągów są porównywane, a dłuższy ciąg jest uznawany za większy. Po trzecie, jeśli długości są równe, używane jest zwykłe porównanie ciągów.

Ciągi List<T> są tworzone i wypełniane nazwami pięciu roślinożernych dinozaurów i trzech mięsożernych dinozaurów. W każdej z tych dwóch grup nazwy nie są w żadnej określonej kolejności sortowania. Zostanie wyświetlona lista, zakres herbyworów jest posortowany przy użyciu alternatywnego porównania, a lista jest wyświetlana ponownie.

BinarySearch(Int32, Int32, T, IComparer<T>) Przeciążenie metody jest następnie używane do wyszukiwania tylko zakresu herbiwarów dla "Brachiosaurus". Nie można odnaleźć ciągu, a dopełnienie bitowe (operator ~ w językach C# i Visual C++, Xor -1 w Języku Visual Basic) liczby ujemnej zwracanej przez BinarySearch(Int32, Int32, T, IComparer<T>) metodę jest używany jako indeks do wstawiania nowego ciągu.

C#
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
 */

Uwagi

Jeśli comparer zostanie podana wartość , elementy List<T> są sortowane przy użyciu określonej IComparer<T> implementacji.

Jeśli comparer to null, domyślny moduł porównujący Comparer<T>.Default sprawdza, czy typ T implementuje IComparable<T> interfejs ogólny i używa tej implementacji, jeśli jest dostępna. Jeśli nie, sprawdza, Comparer<T>.Default czy typ T implementuje IComparable interfejs. Jeśli typ T nie implementuje interfejsu, Comparer<T>.Default zgłasza wartość InvalidOperationException.

Ta metoda używa Array.Sortklasy , która stosuje sortowanie introspektywne w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania

  • Jeśli liczba partycji przekracza 2 dziennik n, gdzie n jest zakresem tablicy wejściowej, używa algorytmu Heapsort .

  • W przeciwnym razie używa algorytmu Quicksort.

Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n to Count.

Zobacz też

Dotyczy

.NET 9 i inne wersje
Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort()

Źródło:
List.cs
Źródło:
List.cs
Źródło:
List.cs

Sortuje elementy w całości List<T> przy użyciu domyślnego modułu porównującego.

C#
public void Sort ();

Wyjątki

Domyślny moduł porównujący Default nie może odnaleźć implementacji interfejsu IComparable<T> ogólnego lub interfejsu IComparable dla typu T.

Przykłady

Poniższy przykład dodaje kilka nazw do List<String> obiektu, wyświetla listę w nieposortowanej kolejności, wywołuje Sort metodę, a następnie wyświetla posortowaną listę.

C#
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

Poniższy kod demonstruje Sort() przeciążenia metody i Sort(Comparison<T>) dla prostego obiektu biznesowego. Sort() Wywołanie metody powoduje użycie domyślnego porównania dla typu część, a Sort(Comparison<T>) metoda jest implementowana przy użyciu metody anonimowej.

C#
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

         */
    }
}

W poniższym przykładzie pokazano Sort() przeciążenie metody i BinarySearch(T) przeciążenie metody. Ciągi List<T> są tworzone i wypełniane czterema ciągami, bez określonej kolejności. Lista jest wyświetlana, posortowana i wyświetlana ponownie.

BinarySearch(T) Przeciążenie metody jest następnie używane do wyszukiwania dwóch ciągów, które nie znajdują się na liście, a Insert metoda jest używana do ich wstawiania. Zwracana wartość BinarySearch metody jest ujemna w każdym przypadku, ponieważ ciągi nie znajdują się na liście. Biorąc bitowe uzupełnienie (operator ~ w językach C# i Visual C++, Xor -1 w Języku Visual Basic) tej liczby ujemnej tworzy indeks pierwszego elementu na liście, który jest większy niż ciąg wyszukiwania, a wstawianie w tej lokalizacji zachowuje kolejność sortowania. Drugi ciąg wyszukiwania jest większy niż dowolny element na liście, więc pozycja wstawiania znajduje się na końcu listy.

C#
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
*/

Uwagi

Ta metoda używa domyślnego modułu porównującego Comparer<T>.Default dla typu T w celu określenia kolejności elementów listy. Właściwość Comparer<T>.Default sprawdza, czy typ T implementuje IComparable<T> interfejs ogólny i używa tej implementacji, jeśli jest dostępna. Jeśli nie, sprawdza, Comparer<T>.Default czy typ T implementuje IComparable interfejs. Jeśli typ T nie implementuje interfejsu, Comparer<T>.Default zgłasza wartość InvalidOperationException.

Ta metoda używa Array.Sort metody , która stosuje sortowanie introspektywne w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania.

  • Jeśli liczba partycji przekracza 2 dziennik n, gdzie n jest zakresem tablicy wejściowej, używa algorytmu Heapsort.

  • W przeciwnym razie używa algorytmu Quicksort.

Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n to Count.

Zobacz też

Dotyczy

.NET 9 i inne wersje
Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort(IComparer<T>)

Źródło:
List.cs
Źródło:
List.cs
Źródło:
List.cs

Sortuje elementy w całości List<T> przy użyciu określonego modułu porównującego.

C#
public void Sort (System.Collections.Generic.IComparer<T> comparer);
C#
public void Sort (System.Collections.Generic.IComparer<T>? comparer);

Parametry

comparer
IComparer<T>

Implementacja IComparer<T> używana podczas porównywania elementów lub null używania domyślnego modułu Defaultporównującego .

Wyjątki

comparer to null, a domyślny moduł porównujący Default nie może odnaleźć implementacji interfejsu IComparable<T> ogólnego lub interfejsu IComparable dla typu T.

Implementacja spowodowała comparer błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

Przykłady

W poniższym przykładzie pokazano Sort(IComparer<T>) przeciążenie metody i BinarySearch(T, IComparer<T>) przeciążenie metody.

W przykładzie zdefiniowano alternatywny moduł porównujący ciągów o nazwie DinoCompare, który implementuje IComparer<string> interfejs ogólny (IComparer(Of String) w języku Visual Basic IComparer<String^> w języku Visual C++). Narzędzie porównujące działa w następujący sposób: najpierw współzależność jest testowana pod kątem nullwartości , a odwołanie o wartości null jest traktowane jako mniejsze niż niepuste. Po drugie, długości ciągów są porównywane, a dłuższy ciąg jest uznawany za większy. Po trzecie, jeśli długości są równe, używane jest zwykłe porównanie ciągów.

Ciągi List<T> są tworzone i wypełniane czterema ciągami, bez określonej kolejności. Zostanie wyświetlona lista, posortowana przy użyciu alternatywnego porównania i wyświetlona ponownie.

BinarySearch(T, IComparer<T>) Przeciążenie metody jest następnie używane do wyszukiwania kilku ciągów, które nie znajdują się na liście, przy użyciu alternatywnego porównania. Metoda Insert służy do wstawiania ciągów. Te dwie metody znajdują się w funkcji o nazwie SearchAndInsert, wraz z kodem, aby pobrać bitowe uzupełnienie (operator ~ w języku C# i Visual C++, Xor -1 w Visual Basic) liczby ujemnej zwracanej przez BinarySearch(T, IComparer<T>) i używać jej jako indeksu do wstawiania nowego ciągu.

C#
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
 */

Uwagi

Jeśli comparer zostanie podana wartość , elementy List<T> są sortowane przy użyciu określonej IComparer<T> implementacji.

Jeśli comparer to null, domyślny moduł porównujący Comparer<T>.Default sprawdza, czy typ T implementuje IComparable<T> interfejs ogólny i używa tej implementacji, jeśli jest dostępna. Jeśli nie, sprawdza, Comparer<T>.Default czy typ T implementuje IComparable interfejs. Jeśli typ T nie implementuje interfejsu, Comparer<T>.Default zgłasza wartość InvalidOperationException.

Ta metoda używa Array.Sort metody , która stosuje sortowanie introspektywne w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania.

  • Jeśli liczba partycji przekracza 2 dziennik n, gdzie n jest zakresem tablicy wejściowej, używa algorytmu Heapsort.

  • W przeciwnym razie używa algorytmu Quicksort.

Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n to Count.

Zobacz też

Dotyczy

.NET 9 i inne wersje
Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0