ArrayList.Sort Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Ordena os elementos no ArrayList ou uma parte dele.
Sobrecargas
| Name | Description |
|---|---|
| Sort() |
Ordena os elementos em todo ArrayListo . |
| Sort(IComparer) |
Ordena os elementos no todo ArrayList usando o comparador especificado. |
| Sort(Int32, Int32, IComparer) |
Ordena os elementos num intervalo de elementos usando ArrayList o comparador especificado. |
Sort()
Ordena os elementos em todo ArrayListo .
public:
virtual void Sort();
public virtual void Sort();
abstract member Sort : unit -> unit
override this.Sort : unit -> unit
Public Overridable Sub Sort ()
Exceções
É ArrayList só de leitura.
Exemplos
O seguinte exemplo de código mostra como ordenar os valores num ArrayList.
using System;
using System.Collections;
public class SamplesArrayList1
{
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("The");
myAL.Add("quick");
myAL.Add("brown");
myAL.Add("fox");
myAL.Add("jumps");
myAL.Add("over");
myAL.Add("the");
myAL.Add("lazy");
myAL.Add("dog");
// Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:");
PrintValues(myAL);
// Sorts the values of the ArrayList.
myAL.Sort();
// Displays the values of the ArrayList.
Console.WriteLine("After sorting:");
PrintValues(myAL);
}
public static void PrintValues(IEnumerable myList)
{
foreach (Object obj in myList)
Console.WriteLine(" {0}", obj);
Console.WriteLine();
}
}
/*
This code produces the following output.
The ArrayList initially contains the following values:
The
quick
brown
fox
jumps
over
the
lazy
dog
After sorting:
brown
dog
fox
jumps
lazy
over
quick
the
The
*/
Imports System.Collections
Public Class SamplesArrayList
Public Shared Sub Main()
' Creates and initializes a new ArrayList.
Dim myAL As New ArrayList()
myAL.Add("The")
myAL.Add("quick")
myAL.Add("brown")
myAL.Add("fox")
myAL.Add("jumps")
myAL.Add("over")
myAL.Add("the")
myAL.Add("lazy")
myAL.Add("dog")
' Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:")
PrintValues(myAL)
' Sorts the values of the ArrayList.
myAL.Sort()
' Displays the values of the ArrayList.
Console.WriteLine("After sorting:")
PrintValues(myAL)
End Sub
Public Shared Sub PrintValues(myList As IEnumerable)
Dim obj As [Object]
For Each obj In myList
Console.WriteLine(" {0}", obj)
Next obj
Console.WriteLine()
End Sub
End Class
' This code produces the following output.
'
' The ArrayList initially contains the following values:
' The
' quick
' brown
' fox
' jumps
' over
' the
' lazy
' dog
'
' After sorting:
' brown
' dog
' fox
' jumps
' lazy
' over
' quick
' the
' The
Observações
Este método utiliza Array.Sort, que utiliza o algoritmo QuickSort. O algoritmo QuickSort é uma ordenação por comparação (também chamada de ordenação instável), o que significa que uma operação de comparação "menor ou igual a" determina qual dos dois elementos deve ocorrer primeiro na lista ordenada final. No entanto, se dois elementos forem iguais, a sua ordem original pode não ser preservada. Em contraste, uma ordenação estável preserva a ordem dos elementos que são iguais. Para realizar uma ordenação estável, deve implementar uma interface personalizada IComparer para usar com as outras sobrecargas deste método.
Em média, este método é uma O(n log n) operação, onde n é Count; no pior caso é uma O(n^2) operação.
Ver também
Aplica-se a
Sort(IComparer)
Ordena os elementos no todo ArrayList usando o comparador especificado.
public:
virtual void Sort(System::Collections::IComparer ^ comparer);
public virtual void Sort(System.Collections.IComparer comparer);
abstract member Sort : System.Collections.IComparer -> unit
override this.Sort : System.Collections.IComparer -> unit
Public Overridable Sub Sort (comparer As IComparer)
Parâmetros
- comparer
- IComparer
A IComparer implementação a usar ao comparar elementos.
-ou-
Uma referência nula (Nothing em Visual Basic) para usar a implementação IComparable de cada elemento.
Exceções
É ArrayList só de leitura.
Ocorreu um erro ao comparar dois elementos.
null é passado por comparer, e os elementos na lista não implementam IComparable.
Exemplos
O exemplo de código seguinte mostra como ordenar os valores em e ArrayList usando o comparador padrão e um comparador personalizado que inverte a ordem de ordenação.
using System;
using System.Collections;
public class SamplesArrayList2
{
public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare(Object x, Object y)
{
return ((new CaseInsensitiveComparer()).Compare(y, x));
}
}
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("The");
myAL.Add("quick");
myAL.Add("brown");
myAL.Add("fox");
myAL.Add("jumps");
myAL.Add("over");
myAL.Add("the");
myAL.Add("lazy");
myAL.Add("dog");
// Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:");
PrintIndexAndValues(myAL);
// Sorts the values of the ArrayList using the default comparer.
myAL.Sort();
Console.WriteLine("After sorting with the default comparer:");
PrintIndexAndValues(myAL);
// Sorts the values of the ArrayList using the reverse case-insensitive comparer.
IComparer myComparer = new myReverserClass();
myAL.Sort(myComparer);
Console.WriteLine("After sorting with the reverse case-insensitive comparer:");
PrintIndexAndValues(myAL);
}
public static void PrintIndexAndValues(IEnumerable myList)
{
int i = 0;
foreach (Object obj in myList)
Console.WriteLine("\t[{0}]:\t{1}", i++, obj);
Console.WriteLine();
}
}
/*
This code produces the following output.
The ArrayList initially contains the following values:
[0]: The
[1]: quick
[2]: brown
[3]: fox
[4]: jumps
[5]: over
[6]: the
[7]: lazy
[8]: dog
After sorting with the default comparer:
[0]: brown
[1]: dog
[2]: fox
[3]: jumps
[4]: lazy
[5]: over
[6]: quick
[7]: the
[8]: The
After sorting with the reverse case-insensitive comparer:
[0]: the
[1]: The
[2]: quick
[3]: over
[4]: lazy
[5]: jumps
[6]: fox
[7]: dog
[8]: brown
*/
Imports System.Collections
Public Class SamplesArrayList
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Public Function Compare( ByVal x As Object, ByVal y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new ArrayList.
Dim myAL As New ArrayList()
myAL.Add("The")
myAL.Add("quick")
myAL.Add("brown")
myAL.Add("fox")
myAL.Add("jumps")
myAL.Add("over")
myAL.Add("the")
myAL.Add("lazy")
myAL.Add("dog")
' Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:")
PrintIndexAndValues(myAL)
' Sorts the values of the ArrayList using the default comparer.
myAL.Sort()
Console.WriteLine("After sorting with the default comparer:")
PrintIndexAndValues(myAL)
' Sorts the values of the ArrayList using the reverse case-insensitive comparer.
Dim myComparer = New myReverserClass()
myAL.Sort(myComparer)
Console.WriteLine("After sorting with the reverse case-insensitive comparer:")
PrintIndexAndValues(myAL)
End Sub
Public Shared Sub PrintIndexAndValues(myList As IEnumerable)
Dim i As Integer = 0
Dim obj As [Object]
For Each obj In myList
Console.WriteLine(vbTab + "[{0}]:" + vbTab + "{1}", i, obj)
i = i + 1
Next obj
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'The ArrayList initially contains the following values:
' [0]: The
' [1]: quick
' [2]: brown
' [3]: fox
' [4]: jumps
' [5]: over
' [6]: the
' [7]: lazy
' [8]: dog
'
'After sorting with the default comparer:
' [0]: brown
' [1]: dog
' [2]: fox
' [3]: jumps
' [4]: lazy
' [5]: over
' [6]: quick
' [7]: the
' [8]: The
'
'After sorting with the reverse case-insensitive comparer:
' [0]: the
' [1]: The
' [2]: quick
' [3]: over
' [4]: lazy
' [5]: jumps
' [6]: fox
' [7]: dog
' [8]: brown
Observações
Use o Sort método para ordenar uma lista de objetos com um comparador personalizado que implemente a IComparer interface. Se passar null por comparer, este método utiliza a IComparable implementação de cada elemento. Neste caso, deve garantir que os objetos contidos na lista implementam a IComparer interface ou ocorre uma exceção.
Além disso, usar a IComparable implementação significa que a lista executa uma ordenação por comparação (também chamada de ordenação instável); ou seja, se dois elementos forem iguais, a sua ordem pode não ser preservada. Em contraste, uma ordenação estável preserva a ordem dos elementos que são iguais. Para realizar uma ordenação estável, deve implementar uma interface personalizada IComparer .
Em média, este método é uma O(n log n) operação, onde n é Count; no pior caso é uma O(n^2) operação.
Ver também
Aplica-se a
Sort(Int32, Int32, IComparer)
Ordena os elementos num intervalo de elementos usando ArrayList o comparador especificado.
public:
virtual void Sort(int index, int count, System::Collections::IComparer ^ comparer);
public virtual void Sort(int index, int count, System.Collections.IComparer comparer);
abstract member Sort : int * int * System.Collections.IComparer -> unit
override this.Sort : int * int * System.Collections.IComparer -> unit
Public Overridable Sub Sort (index As Integer, count As Integer, comparer As IComparer)
Parâmetros
- index
- Int32
O índice inicial baseado em zero do intervalo a ordenar.
- count
- Int32
O comprimento do intervalo para ordenar.
- comparer
- IComparer
A IComparer implementação a usar ao comparar elementos.
-ou-
Uma referência nula (Nothing em Visual Basic) para usar a implementação IComparable de cada elemento.
Exceções
index e count não especifiquem um intervalo válido no ArrayList.
É ArrayList só de leitura.
Ocorreu um erro ao comparar dois elementos.
Exemplos
O exemplo de código seguinte mostra como ordenar os valores num intervalo de elementos em e ArrayList usando o comparador padrão e um comparador personalizado que inverte a ordem de ordenação.
using System;
using System.Collections;
public class SamplesArrayList3
{
public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare(Object x, Object y)
{
return ((new CaseInsensitiveComparer()).Compare(y, x));
}
}
public static void Main()
{
// Creates and initializes a new ArrayList.
ArrayList myAL = new ArrayList();
myAL.Add("The");
myAL.Add("QUICK");
myAL.Add("BROWN");
myAL.Add("FOX");
myAL.Add("jumps");
myAL.Add("over");
myAL.Add("the");
myAL.Add("lazy");
myAL.Add("dog");
// Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:");
PrintIndexAndValues(myAL);
// Sorts the values of the ArrayList using the default comparer.
myAL.Sort(1, 3, null);
Console.WriteLine("After sorting from index 1 to index 3 with the default comparer:");
PrintIndexAndValues(myAL);
// Sorts the values of the ArrayList using the reverse case-insensitive comparer.
IComparer myComparer = new myReverserClass();
myAL.Sort(1, 3, myComparer);
Console.WriteLine("After sorting from index 1 to index 3 with the reverse case-insensitive comparer:");
PrintIndexAndValues(myAL);
}
public static void PrintIndexAndValues(IEnumerable myList)
{
int i = 0;
foreach (Object obj in myList)
Console.WriteLine("\t[{0}]:\t{1}", i++, obj);
Console.WriteLine();
}
}
/*
This code produces the following output.
The ArrayList initially contains the following values:
[0]: The
[1]: QUICK
[2]: BROWN
[3]: FOX
[4]: jumps
[5]: over
[6]: the
[7]: lazy
[8]: dog
After sorting from index 1 to index 3 with the default comparer:
[0]: The
[1]: BROWN
[2]: FOX
[3]: QUICK
[4]: jumps
[5]: over
[6]: the
[7]: lazy
[8]: dog
After sorting from index 1 to index 3 with the reverse case-insensitive comparer:
[0]: The
[1]: QUICK
[2]: FOX
[3]: BROWN
[4]: jumps
[5]: over
[6]: the
[7]: lazy
[8]: dog
*/
Imports System.Collections
Public Class SamplesArrayList
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Public Function Compare( ByVal x As Object, ByVal y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new ArrayList.
Dim myAL As New ArrayList()
myAL.Add("The")
myAL.Add("QUICK")
myAL.Add("BROWN")
myAL.Add("FOX")
myAL.Add("jumps")
myAL.Add("over")
myAL.Add("the")
myAL.Add("lazy")
myAL.Add("dog")
' Displays the values of the ArrayList.
Console.WriteLine("The ArrayList initially contains the following values:")
PrintIndexAndValues(myAL)
' Sorts the values of the ArrayList using the default comparer.
myAL.Sort(1, 3, Nothing)
Console.WriteLine("After sorting from index 1 to index 3 with the default comparer:")
PrintIndexAndValues(myAL)
' Sorts the values of the ArrayList using the reverse case-insensitive comparer.
Dim myComparer = New myReverserClass()
myAL.Sort(1, 3, myComparer)
Console.WriteLine("After sorting from index 1 to index 3 with the reverse case-insensitive comparer:")
PrintIndexAndValues(myAL)
End Sub
Public Shared Sub PrintIndexAndValues(myList As IEnumerable)
Dim i As Integer = 0
Dim obj As [Object]
For Each obj In myList
Console.WriteLine(vbTab + "[{0}]:" + vbTab + "{1}", i, obj)
i = i + 1
Next obj
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'The ArrayList initially contains the following values:
' [0]: The
' [1]: QUICK
' [2]: BROWN
' [3]: FOX
' [4]: jumps
' [5]: over
' [6]: the
' [7]: lazy
' [8]: dog
'
'After sorting from index 1 to index 3 with the default comparer:
' [0]: The
' [1]: BROWN
' [2]: FOX
' [3]: QUICK
' [4]: jumps
' [5]: over
' [6]: the
' [7]: lazy
' [8]: dog
'
'After sorting from index 1 to index 3 with the reverse case-insensitive comparer:
' [0]: The
' [1]: QUICK
' [2]: FOX
' [3]: BROWN
' [4]: jumps
' [5]: over
' [6]: the
' [7]: lazy
' [8]: dog
Observações
Se comparer for definido como null, este método realiza uma ordenação por comparação (também chamada de ordenação instável); isto é, se dois elementos forem iguais, a sua ordem pode não ser preservada. Em contraste, uma ordenação estável preserva a ordem dos elementos que são iguais. Para realizar uma ordenação estável, deve implementar uma interface personalizada IComparer .
Em média, este método é uma O(n log n) operação, onde n é count; no pior caso é uma O(n^2) operação.