Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
Clase genérica SortedList

Nota: esta clase es nueva en la versión 2.0 de .NET Framework.

Representa una colección de pares clave/valor que se ordenan conforme a la clave basándose en la implementación de IComparer asociada.

Espacio de nombres: System.Collections.Generic
Ensamblado: System (en system.dll)

Visual Basic (Declaración)
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class SortedList(Of TKey, TValue)
    Implements IDictionary(Of TKey, TValue), ICollection(Of KeyValuePair(Of TKey, TValue)), _
    IEnumerable(Of KeyValuePair(Of TKey, TValue)), IDictionary, ICollection, _
    IEnumerable
Visual Basic (Uso)
Dim instance As SortedList(Of TKey, TValue)
C#
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class SortedList<TKey,TValue> : IDictionary<TKey,TValue>, ICollection<KeyValuePair<TKey,TValue>>, 
    IEnumerable<KeyValuePair<TKey,TValue>>, IDictionary, ICollection, IEnumerable
C++
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename TKey, typename TValue>
public ref class SortedList : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, 
    IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
J#
J# admite el uso de métodos y tipos genéricos, pero no admite la declaración de métodos y tipos nuevos.
JScript
JScript no admite el uso de métodos y tipos genéricos.

Parámetros de tipo

TKey

Tipo de claves de la colección.

TValue

Tipo de valores de la colección.

La clase genérica SortedList es un árbol de búsqueda binaria que recupera mediante O(logn), donde n es el número de elementos del diccionario. En este aspecto, es similar a la clase genérica SortedDictionary. Las dos clases tienen modelos de objetos similares y ambas recuperan mediante O(log n). En lo que se diferencian las dos clases es en el uso de memoria y en la velocidad de inserción y eliminación:

  • SortedList utiliza menos memoria que SortedDictionary.

  • Las operaciones de inserción y eliminación de SortedDictionary para los datos no ordenados son más rápidas: operaciones O(log n) frente a las operaciones O(n) de SortedList.

  • Si la lista se rellena de una sola vez de datos ordenados, la colección SortedList es más rápida que SortedDictionary.

Otra diferencia entre las clases SortedDictionary y SortedList es que SortedList admite la recuperación indizada eficaz de claves y valores mediante las colecciones que devuelven las propiedades Keys y Values. Cuando se obtiene acceso a las propiedades, no es necesario volver a generar las listas puesto que éstas únicamente son contenedores para las matrices internas de claves y valores. En el código siguiente se muestra el uso de la propiedad Values para la recuperación indizada de valores de una lista ordenada de cadenas:

Visual Basic
Dim v As String = mySortedList.Values(3)
C#
string v = mySortedList.Values[3];
C++
String^ v = mySortedList->Values[3];

SortedList se implementa como una matriz de pares clave/valor, ordenada conforme a la clave. Cada elemento se puede recuperar como un objeto KeyValuePair.

Los objetos de claves deben permanecer inmutables mientras se utilicen como claves en SortedList. Todas las claves de una colección SortedList deben ser únicas. Una clave no puede ser referencia de objeto null (Nothing en Visual Basic), pero un valor sí puede serlo si el tipo de los valores de la lista, TValue, es un tipo de referencia.

SortedList requiere la implementación de un comparador para ordenar y realizar comparaciones. El comparador predeterminado Comparer.Default comprueba si el tipo de clave TKey implementa System.IComparable y utiliza esa implementación, si está disponible. En caso contrario, Comparer.Default comprueba si el tipo de clave TKey implementa System.IComparable. Si el tipo de clave TKey no implementa ninguna de las interfaces, se puede especificar una implementación de System.Collections.Generic.IComparer en una sobrecarga de constructor que acepte un parámetro comparer.

La capacidad de una colección SortedList es el número de elementos que dicha SortedList puede contener. En esta implementación, la capacidad inicial predeterminada para una colección SortedList es 16; sin embargo, ese valor predeterminado quizás cambie en las versiones futuras de .NET Framework. Cuando se agregan elementos a una colección SortedList, la capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna. La capacidad se puede disminuir si se llama al método TrimExcess o si se establece explícitamente la propiedad Capacity. Al disminuir la capacidad se reasigna memoria y se copian todos los elementos de la colección SortedList.

La instrucción foreach del lenguaje C# (for each en C++, For Each en Visual Basic) requiere el tipo de los elementos de la colección. Como los elementos de SortedList son pares clave/valor, el tipo del elemento no se corresponde con el tipo de la clave, ni con el del valor. En su lugar, el tipo del elemento es KeyValuePair. Por ejemplo:

C#
foreach (KeyValuePair<int, string> kvp in mySortedList) {...}
C++
for each (KeyValuePair<int, String^> kvp in mySortedList) {...}
Visual Basic
For Each kvp As KeyValuePair(Of Integer, String) In mySortedList
    ...
Next kvp

La instrucción foreach es un contenedor del enumerador, que sólo permite la lectura pero no la escritura en la colección.

En el ejemplo de código siguiente se crea una colección SortedList vacía de cadenas con claves de cadena y se utiliza el método Add para agregar algunos elementos. En él, se muestra que el método Add produce una excepción ArgumentException cuando se intenta agregar una clave duplicada.

Asimismo, se utiliza la propiedad Item (el indizador en C#) para recuperar los valores, mostrando que se produce una excepción KeyNotFoundException cuando no está presente una clave solicitada, y que se puede reemplazar el valor asociado a una clave.

En el ejemplo se muestra cómo utilizar el método TryGetValue como un medio más eficaz para recuperar valores si un programa debe probar con frecuencia valores de clave que no están en la lista ordenada, y cómo utilizar el método ContainsKey para comprobar si una clave existe antes de llamar al método Add.

Además, en el ejemplo se muestra cómo enumerar las claves y los valores de la lista ordenada, y cómo enumerar sólo las claves y los valores utilizando la propiedad Keys y la propiedad Values.

Por último, en el ejemplo se muestra el método Remove.

Visual Basic
Imports System
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted list of strings, with string 
        ' keys. 
        Dim openWith As New SortedList(Of String, String)
        
        ' Add some elements to the list. There are no 
        ' duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' The Add method throws an exception if the new key is 
        ' already in the list.
        Try
            openWith.Add("txt", "winword.exe")
        Catch 
            Console.WriteLine("An element with Key = ""txt"" already exists.")
        End Try

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' The default Item property throws an exception if the requested
        ' key is not in the list.
        Try
            Console.WriteLine("For key = ""tif"", value = {0}.", _
                openWith("tif"))
        Catch 
            Console.WriteLine("Key = ""tif"" is not found.")
        End Try

        ' When a program often has to try keys that turn out not to
        ' be in the list, TryGetValue can be a more efficient 
        ' way to retrieve values.
        Dim value As String = ""
        If openWith.TryGetValue("tif", value) Then
            Console.WriteLine("For key = ""tif"", value = {0}.", value)
        Else
            Console.WriteLine("Key = ""tif"" is not found.")
        End If

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
                openWith("ht"))
        End If

        ' When you use foreach to enumerate list elements,
        ' the elements are retrieved as KeyValuePair objects.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

        ' To get the values alone, use the Values property.
        Dim ilistValues As IList(Of String) = openWith.Values
        
        ' The elements of the list are strongly typed with the
        ' type that was specified for the SortedList values.
        Console.WriteLine()
        For Each s As String In ilistValues
            Console.WriteLine("Value = {0}", s)
        Next s

        ' The Values property is an efficient way to retrieve
        ' values by index.
        Console.WriteLine(vbLf & "Indexed retrieval using the " & _
            "Values property: Values(2) = {0}", openWith.Values(2))

        ' To get the keys alone, use the Keys property.
        Dim ilistKeys As IList(Of String) = openWith.Keys
        
        ' The elements of the list are strongly typed with the
        ' type that was specified for the SortedList keys.
        Console.WriteLine()
        For Each s As String In ilistKeys 
            Console.WriteLine("Key = {0}", s)
        Next s

        ' The Keys property is an efficient way to retrieve
        ' keys by index.
        Console.WriteLine(vbLf & "Indexed retrieval using the " & _
            "Keys property: Keys(2) = {0}", openWith.Keys(2))

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        openWith.Remove("doc")
        
        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Class

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Key = "tif" is not found.
'Key = "tif" is not found.
'Value added for key = "ht": hypertrm.exe
'
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'Key = rtf, Value = winword.exe
'Key = txt, Value = notepad.exe
'
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = hypertrm.exe
'Value = winword.exe
'Value = notepad.exe
'
'Indexed retrieval using the Values property: Values(2) = winword.exe
'
'Key = bmp
'Key = dib
'Key = doc
'Key = ht
'Key = rtf
'Key = txt
'
'Indexed retrieval using the Keys property: Keys(2) = doc
'
'Remove("doc")
'Key "doc" is not found.
' 
C#
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted list of strings, with string
        // keys.
        SortedList<string, string> openWith = 
            new SortedList<string, string>();

        // Add some elements to the list. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the list.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is another name for the indexer, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the list.
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", 
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the list, TryGetValue can be a more efficient 
        // way to retrieve values.
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", 
                openWith["ht"]);
        }

        // When you use foreach to enumerate list elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        IList<string> ilistValues = openWith.Values;

        // The elements of the list are strongly typed with the 
        // type that was specified for the SorteList values.
        Console.WriteLine();
        foreach( string s in ilistValues )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // The Values property is an efficient way to retrieve
        // values by index.
        Console.WriteLine("\nIndexed retrieval using the Values " +
            "property: Values[2] = {0}", openWith.Values[2]);

        // To get the keys alone, use the Keys property.
        IList<string> ilistKeys = openWith.Keys;

        // The elements of the list are strongly typed with the 
        // type that was specified for the SortedList keys.
        Console.WriteLine();
        foreach( string s in ilistKeys )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // The Keys property is an efficient way to retrieve
        // keys by index.
        Console.WriteLine("\nIndexed retrieval using the Keys " +
            "property: Keys[2] = {0}", openWith.Keys[2]);

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe

Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe

Indexed retrieval using the Values property: Values[2] = winword.exe

Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt

Indexed retrieval using the Keys property: Keys[2] = doc

Remove("doc")
Key "doc" is not found.
 */
System.Object
  System.Collections.Generic.SortedList

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

SortedList puede admitir varios sistemas de lectura a la vez, siempre y cuando no se modifique la colección. Aun así, por su naturaleza, la enumeración mediante una colección no es un procedimiento seguro para la ejecución de subprocesos. Para garantizar la seguridad para la ejecución de subprocesos durante la enumeración, puede bloquear la colección durante toda la enumeración. Para permitir que varios subprocesos obtengan acceso de lectura y escritura a la colección, debe implementar su propia sincronización.

Windows 98, Windows 2000 SP4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0

.NET Compact Framework

Compatible con: 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker