Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Metodo List<T>.Sort (Int32, Int32, IComparer<T>)

 

Ordina gli elementi di un intervallo di elementi di List<T> usando l'operatore di confronto specificato.

Spazio dei nomi:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

public void Sort(
	int index,
	int count,
	IComparer<T> comparer
)

Parametri

index
Type: System.Int32

Indice iniziale in base zero dell'intervallo da ordinare.

count
Type: System.Int32

Lunghezza dell'intervallo da ordinare.

comparer
Type: System.Collections.Generic.IComparer<T>

Implementazione IComparer<T> da usare durante il confronto di elementi oppure null per usare la proprietà Comparer<T>.Default dell'operatore di confronto.

Exception Condition
ArgumentOutOfRangeException

index è minore di 0.

-oppure-

count è minore di 0.

ArgumentException

index e count non specificano un intervallo valido in List<T>.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

InvalidOperationException

comparer è null e l'operatore di confronto predefinito Comparer<T>.Default non riesce a trovare l'implementazione dell'interfaccia generica IComparable<T> o l'interfaccia IComparable per il tipo T.

If comparer is provided, the elements of the T:System.Collections.Generic.List`1 are sorted using the specified T:System.Collections.Generic.IComparer`1 implementation.

If comparer is null, the default comparer P:System.Collections.Generic.Comparer`1.Default checks whether type T implements the T:System.IComparable`1 generic interface and uses that implementation, if available. If not, P:System.Collections.Generic.Comparer`1.Default checks whether type T implements the T:System.IComparable interface. If type T does not implement either interface, P:System.Collections.Generic.Comparer`1.Default throws an T:System.InvalidOperationException.

This method uses M:System.Array.Sort(System.Array,System.Int32,System.Int32,System.Collections.IComparer), which applies the introspective sort as follows:

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

  • If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsorthttp://en.wikipedia.org/wiki/Heapsort  algorithm.

  • Otherwise, it uses a Quicksort algorithm.

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

On average, this method is an O(n log n) operation, where n is P:System.Collections.Generic.List`1.Count; in the worst case it is an O(n ^ 2) operation.

The following example demonstrates the M:System.Collections.Generic.List`1.Sort(System.Int32,System.Int32,System.Collections.Generic.IComparer{`0}) method overload and the M:System.Collections.Generic.List`1.BinarySearch(System.Int32,System.Int32,`0,System.Collections.Generic.IComparer{`0}) method overload.

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

A T:System.Collections.Generic.List`1 of strings is created and populated with the names of five herbivorous dinosaurs and three carnivorous dinosaurs. Within each of the two groups, the names are not in any particular sort order. The list is displayed, the range of herbivores is sorted using the alternate comparer, and the list is displayed again.

The M:System.Collections.Generic.List`1.BinarySearch(System.Int32,System.Int32,`0,System.Collections.Generic.IComparer{`0}) method overload is then used to search only the range of herbivores for "Brachiosaurus". 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 M:System.Collections.Generic.List`1.BinarySearch(System.Int32,System.Int32,`0,System.Collections.Generic.IComparer{`0}) method is used as an index for inserting the new string.

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

Universal Windows Platform
Disponibile da 8
.NET Framework
Disponibile da 2.0
Libreria di classi portabile
Supportato in: piattaforme .NET portabili
Silverlight
Disponibile da 2.0
Windows Phone Silverlight
Disponibile da 7.0
Windows Phone
Disponibile da 8.1
Torna all'inizio
Mostra: