OrderedDictionary Class

Definition

Representa una colección de pares de clave y valor a los que se puede tener acceso por clave o por índice.Represents a collection of key/value pairs that are accessible by the key or index.

public ref class OrderedDictionary : System::Collections::IDictionary, System::Collections::Specialized::IOrderedDictionary
public ref class OrderedDictionary : System::Collections::IDictionary, System::Collections::Specialized::IOrderedDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public ref class OrderedDictionary : System::Collections::Specialized::IOrderedDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
public class OrderedDictionary : System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type OrderedDictionary = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface IOrderedDictionary
type OrderedDictionary = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface IOrderedDictionary
    interface IDeserializationCallback
    interface ISerializable
type OrderedDictionary = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface IOrderedDictionary
    interface ISerializable
    interface IDeserializationCallback
type OrderedDictionary = class
    interface IOrderedDictionary
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
type OrderedDictionary = class
    interface IOrderedDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface IDictionary
    interface ICollection
    interface IEnumerable
Public Class OrderedDictionary
Implements IDictionary, IOrderedDictionary
Public Class OrderedDictionary
Implements IDeserializationCallback, IDictionary, IOrderedDictionary, ISerializable
Public Class OrderedDictionary
Implements IDeserializationCallback, IOrderedDictionary, ISerializable
Inheritance
OrderedDictionary
Derived
Attributes
Implements

Examples

En el ejemplo de código siguiente se muestra la creación, el rellenado y la modificación de una colección de OrderedDictionary, así como dos técnicas para mostrar el contenido de la OrderedDictionary: una con las propiedades Keys y Values, y la otra creación de un enumerador mediante el método GetEnumerator.The following code example demonstrates the creation, population and modification of an OrderedDictionary collection, as well as two techniques to display the contents of the OrderedDictionary: one using the Keys and Values properties and the other creating an enumerator through the GetEnumerator method.

// The following code example enumerates the elements of a OrderedDictionary.
#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;

public ref class OrderedDictionarySample
{
public:
    static void Main()
    {
        // Creates and initializes a OrderedDictionary.
        OrderedDictionary^ myOrderedDictionary = gcnew OrderedDictionary();
        myOrderedDictionary->Add("testKey1", "testValue1");
        myOrderedDictionary->Add("testKey2", "testValue2");
        myOrderedDictionary->Add("keyToDelete", "valueToDelete");
        myOrderedDictionary->Add("testKey3", "testValue3");

        ICollection^ keyCollection = myOrderedDictionary->Keys;
        ICollection^ valueCollection = myOrderedDictionary->Values;

        // Display the contents using the key and value collections
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary->Count);

        // Modifying the OrderedDictionary
        if (!myOrderedDictionary->IsReadOnly)
        {
            // Insert a new key to the beginning of the OrderedDictionary
            myOrderedDictionary->Insert(0, "insertedKey1", "insertedValue1");

            // Modify the value of the entry with the key "testKey2"
            myOrderedDictionary["testKey2"] = "modifiedValue";

            // Remove the last entry from the OrderedDictionary: "testKey3"
            myOrderedDictionary->RemoveAt(myOrderedDictionary->Count - 1);

            // Remove the "keyToDelete" entry, if it exists
            if (myOrderedDictionary->Contains("keyToDelete"))
            {
                myOrderedDictionary->Remove("keyToDelete");
            }
        }

        Console::WriteLine(
            "{0}Displaying the entries of a modified OrderedDictionary.",
            Environment::NewLine);
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary->Count);

        // Clear the OrderedDictionary and add new values
        myOrderedDictionary->Clear();
        myOrderedDictionary->Add("newKey1", "newValue1");
        myOrderedDictionary->Add("newKey2", "newValue2");
        myOrderedDictionary->Add("newKey3", "newValue3");

        // Display the contents of the "new" Dictionary using an enumerator
        IDictionaryEnumerator^ myEnumerator =
            myOrderedDictionary->GetEnumerator();

        Console::WriteLine(
            "{0}Displaying the entries of a \"new\" OrderedDictionary.",
            Environment::NewLine);

        DisplayEnumerator(myEnumerator);

        Console::ReadLine();
    }

    // Displays the contents of the OrderedDictionary from its keys and values
    static void DisplayContents(
        ICollection^ keyCollection, ICollection^ valueCollection, int dictionarySize)
    {
        array<String^>^ myKeys = gcnew array<String^>(dictionarySize);
        array<String^>^ myValues = gcnew array<String^>(dictionarySize);
        keyCollection->CopyTo(myKeys, 0);
        valueCollection->CopyTo(myValues, 0);

        // Displays the contents of the OrderedDictionary
        Console::WriteLine("   INDEX KEY                       VALUE");
        for (int i = 0; i < dictionarySize; i++)
        {
            Console::WriteLine("   {0,-5} {1,-25} {2}",
                i, myKeys[i], myValues[i]);
        }
        Console::WriteLine();
    }

    // Displays the contents of the OrderedDictionary using its enumerator
    static void DisplayEnumerator(IDictionaryEnumerator^ myEnumerator)
    {
        Console::WriteLine("   KEY                       VALUE");
        while (myEnumerator->MoveNext())
        {
            Console::WriteLine("   {0,-25} {1}",
                myEnumerator->Key, myEnumerator->Value);
        }
    }
};

int main()
{
    OrderedDictionarySample::Main();
}

/*
This code produces the following output.

   INDEX KEY                       VALUE
   0     testKey1                  testValue1
   1     testKey2                  testValue2
   2     keyToDelete               valueToDelete
   3     testKey3                  testValue3


Displaying the entries of a modified OrderedDictionary.
   INDEX KEY                       VALUE
   0     insertedKey1              insertedValue1
   1     testKey1                  testValue1
   2     testKey2                  modifiedValue


Displaying the entries of a "new" OrderedDictionary.
   KEY                       VALUE
   newKey1                   newValue1
   newKey2                   newValue2
   newKey3                   newValue3

*/
// The following code example enumerates the elements of a OrderedDictionary.
using System;
using System.Collections;
using System.Collections.Specialized;

public class OrderedDictionarySample
{
    public static void Main()
    {

        // Creates and initializes a OrderedDictionary.
        OrderedDictionary myOrderedDictionary = new OrderedDictionary();
        myOrderedDictionary.Add("testKey1", "testValue1");
        myOrderedDictionary.Add("testKey2", "testValue2");
        myOrderedDictionary.Add("keyToDelete", "valueToDelete");
        myOrderedDictionary.Add("testKey3", "testValue3");

        ICollection keyCollection = myOrderedDictionary.Keys;
        ICollection valueCollection = myOrderedDictionary.Values;

        // Display the contents using the key and value collections
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);

        // Modifying the OrderedDictionary
        if (!myOrderedDictionary.IsReadOnly)
        {
            // Insert a new key to the beginning of the OrderedDictionary
            myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1");

            // Modify the value of the entry with the key "testKey2"
            myOrderedDictionary["testKey2"] = "modifiedValue";

            // Remove the last entry from the OrderedDictionary: "testKey3"
            myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1);

            // Remove the "keyToDelete" entry, if it exists
            if (myOrderedDictionary.Contains("keyToDelete"))
            {
                myOrderedDictionary.Remove("keyToDelete");
            }
        }

        Console.WriteLine(
            "{0}Displaying the entries of a modified OrderedDictionary.",
            Environment.NewLine);
        DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);

        // Clear the OrderedDictionary and add new values
        myOrderedDictionary.Clear();
        myOrderedDictionary.Add("newKey1", "newValue1");
        myOrderedDictionary.Add("newKey2", "newValue2");
        myOrderedDictionary.Add("newKey3", "newValue3");

        // Display the contents of the "new" Dictionary using an enumerator
        IDictionaryEnumerator myEnumerator =
            myOrderedDictionary.GetEnumerator();

        Console.WriteLine(
            "{0}Displaying the entries of a \"new\" OrderedDictionary.",
            Environment.NewLine);

        DisplayEnumerator(myEnumerator);

        Console.ReadLine();
    }

    // Displays the contents of the OrderedDictionary from its keys and values
    public static void DisplayContents(
        ICollection keyCollection, ICollection valueCollection, int dictionarySize)
    {
        String[] myKeys = new String[dictionarySize];
        String[] myValues = new String[dictionarySize];
        keyCollection.CopyTo(myKeys, 0);
        valueCollection.CopyTo(myValues, 0);

        // Displays the contents of the OrderedDictionary
        Console.WriteLine("   INDEX KEY                       VALUE");
        for (int i = 0; i < dictionarySize; i++)
        {
            Console.WriteLine("   {0,-5} {1,-25} {2}",
                i, myKeys[i], myValues[i]);
        }
        Console.WriteLine();
    }

    // Displays the contents of the OrderedDictionary using its enumerator
    public static void DisplayEnumerator(IDictionaryEnumerator myEnumerator)
    {
        Console.WriteLine("   KEY                       VALUE");
        while (myEnumerator.MoveNext())
        {
            Console.WriteLine("   {0,-25} {1}",
                myEnumerator.Key, myEnumerator.Value);
        }
    }
}

/*
This code produces the following output.

   INDEX KEY                       VALUE
   0     testKey1                  testValue1
   1     testKey2                  testValue2
   2     keyToDelete               valueToDelete
   3     testKey3                  testValue3


Displaying the entries of a modified OrderedDictionary.
   INDEX KEY                       VALUE
   0     insertedKey1              insertedValue1
   1     testKey1                  testValue1
   2     testKey2                  modifiedValue


Displaying the entries of a "new" OrderedDictionary.
   KEY                       VALUE
   newKey1                   newValue1
   newKey2                   newValue2
   newKey3                   newValue3

*/
' The following code example enumerates the elements of a OrderedDictionary.
Imports System.Collections
Imports System.Collections.Specialized

Public Class OrderedDictionarySample

    Public Shared Sub Main()

        ' Creates and initializes a OrderedDictionary.
        Dim myOrderedDictionary As New OrderedDictionary()
        myOrderedDictionary.Add("testKey1", "testValue1")
        myOrderedDictionary.Add("testKey2", "testValue2")
        myOrderedDictionary.Add("keyToDelete", "valueToDelete")
        myOrderedDictionary.Add("testKey3", "testValue3")

        Dim keyCollection As ICollection = myOrderedDictionary.Keys
        Dim valueCollection As ICollection = myOrderedDictionary.Values

        ' Display the contents Imports the key and value collections
        DisplayContents( _
            keyCollection, valueCollection, myOrderedDictionary.Count)

        ' Modifying the OrderedDictionary
        If Not myOrderedDictionary.IsReadOnly Then

            ' Insert a new key to the beginning of the OrderedDictionary
            myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1")

            ' Modify the value of the entry with the key "testKey2"
            myOrderedDictionary("testKey2") = "modifiedValue"

            ' Remove the last entry from the OrderedDictionary: "testKey3"
            myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1)

            ' Remove the "keyToDelete" entry, if it exists
            If (myOrderedDictionary.Contains("keyToDelete")) Then
                myOrderedDictionary.Remove("keyToDelete")
            End If
        End If

        Console.WriteLine( _
            "{0}Displaying the entries of a modified OrderedDictionary.", _
            Environment.NewLine)
        DisplayContents( _
            keyCollection, valueCollection, myOrderedDictionary.Count)

        ' Clear the OrderedDictionary and add new values
        myOrderedDictionary.Clear()
        myOrderedDictionary.Add("newKey1", "newValue1")
        myOrderedDictionary.Add("newKey2", "newValue2")
        myOrderedDictionary.Add("newKey3", "newValue3")

        ' Display the contents of the "new" Dictionary Imports an enumerator
        Dim myEnumerator As IDictionaryEnumerator = _
            myOrderedDictionary.GetEnumerator()

        Console.WriteLine( _
            "{0}Displaying the entries of a 'new' OrderedDictionary.", _
            Environment.NewLine)

        DisplayEnumerator(myEnumerator)

        Console.ReadLine()
    End Sub

    ' Displays the contents of the OrderedDictionary from its keys and values
    Public Shared Sub DisplayContents( _
        ByVal keyCollection As ICollection, _
        ByVal valueCollection As ICollection, ByVal dictionarySize As Integer)

        Dim myKeys(dictionarySize) As [String]
        Dim myValues(dictionarySize) As [String]
        keyCollection.CopyTo(myKeys, 0)
        valueCollection.CopyTo(myValues, 0)

        ' Displays the contents of the OrderedDictionary
        Console.WriteLine("   INDEX KEY                       VALUE")
        Dim i As Integer
        For i = 0 To dictionarySize - 1
            Console.WriteLine("   {0,-5} {1,-25} {2}", _
                 i, myKeys(i), myValues(i))
        Next i
        Console.WriteLine()
    End Sub

    ' Displays the contents of the OrderedDictionary using its enumerator
    Public Shared Sub DisplayEnumerator( _
        ByVal myEnumerator As IDictionaryEnumerator)

        Console.WriteLine("   KEY                       VALUE")
        While myEnumerator.MoveNext()
            Console.WriteLine("   {0,-25} {1}", _
                myEnumerator.Key, myEnumerator.Value)
        End While
    End Sub
End Class

'This code produces the following output.
'
'   INDEX KEY                       VALUE
'0:              testKey1(testValue1)
'1:              testKey2(testValue2)
'2:              keyToDelete(valueToDelete)
'3:              testKey3(testValue3)
'
'
'Displaying the entries of a modified OrderedDictionary.
'   INDEX KEY                       VALUE
'0:              insertedKey1(insertedValue1)
'1:              testKey1(testValue1)
'2:              testKey2(modifiedValue)
'
'
'Displaying the entries of a "new" OrderedDictionary.
'                KEY(VALUE)
'                newKey1(newValue1)
'                newKey2(newValue2)
'                newKey3(newValue3)

Remarks

Cada elemento es un par clave-valor almacenado en un objeto DictionaryEntry.Each element is a key/value pair stored in a DictionaryEntry object. No se puede nulluna clave, pero un valor puede ser.A key cannot be null, but a value can be.

Los elementos de una OrderedDictionary no se ordenan por la clave, a diferencia de los elementos de una clase SortedDictionary<TKey,TValue>.The elements of an OrderedDictionary are not sorted by the key, unlike the elements of a SortedDictionary<TKey,TValue> class. Puede tener acceso a los elementos por la clave o por el índice.You can access elements either by the key or by the index.

La instrucción foreach del C# lenguaje (For Each en Visual Basic) devuelve objetos que son del tipo de cada elemento de la colección.The foreach statement of the C# language (For Each in Visual Basic) returns objects that are of the type of each element in the collection. Puesto que cada elemento de la colección OrderedDictionary es un par clave-valor, el tipo de elemento no es el tipo de la clave o el tipo del valor.Since each element of the OrderedDictionary collection is a key/value pair, the element type is not the type of the key or the type of the value. En su lugar, el tipo de elemento es DictionaryEntry.Instead, the element type is DictionaryEntry. En el código siguiente C#se muestra, C++ Visual Basic y sintaxis.The following code shows C#, Visual Basic and C++ syntax.

for each (DictionaryEntry de in myOrderedDictionary)
{
    //...
}
foreach (DictionaryEntry de in myOrderedDictionary)
{
    //...
}
For Each de As DictionaryEntry In myOrderedDictionary
    '...
Next de

La instrucción foreach es un contenedor alrededor del enumerador, que solo permite la lectura, no la escritura, de la colección.The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Constructors

OrderedDictionary()

Inicializa una nueva instancia de la clase OrderedDictionary.Initializes a new instance of the OrderedDictionary class.

OrderedDictionary(IEqualityComparer)

Inicializa una nueva instancia de la clase OrderedDictionary con el comparador especificado.Initializes a new instance of the OrderedDictionary class using the specified comparer.

OrderedDictionary(Int32)

Inicializa una nueva instancia de la clase OrderedDictionary con la capacidad inicial especificada.Initializes a new instance of the OrderedDictionary class using the specified initial capacity.

OrderedDictionary(Int32, IEqualityComparer)

Inicializa una nueva instancia de la clase OrderedDictionary con la capacidad inicial y el comparador especificados.Initializes a new instance of the OrderedDictionary class using the specified initial capacity and comparer.

OrderedDictionary(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase OrderedDictionary que se puede serializar utilizando los objetos SerializationInfo y StreamingContext especificados.Initializes a new instance of the OrderedDictionary class that is serializable using the specified SerializationInfo and StreamingContext objects.

Properties

Count

Obtiene el número de pares clave-valor incluidos en la colección OrderedDictionary.Gets the number of key/values pairs contained in the OrderedDictionary collection.

IsReadOnly

Obtiene un valor que indica si la colección OrderedDictionary es de solo lectura.Gets a value indicating whether the OrderedDictionary collection is read-only.

Item[Int32]

Obtiene o establece el valor en el índice especificado.Gets or sets the value at the specified index.

Item[Object]

Obtiene o establece el valor con la clave especificada.Gets or sets the value with the specified key.

Keys

Obtiene un objeto ICollection que contiene las claves de la colección OrderedDictionary.Gets an ICollection object containing the keys in the OrderedDictionary collection.

Values

Obtiene un objeto ICollection que contiene los valores de la colección OrderedDictionary.Gets an ICollection object containing the values in the OrderedDictionary collection.

Methods

Add(Object, Object)

Agrega una entrada con la clave y el valor especificados a la colección OrderedDictionary, en el índice más bajo que esté disponible.Adds an entry with the specified key and value into the OrderedDictionary collection with the lowest available index.

AsReadOnly()

Devuelve una copia de solo lectura de la colección OrderedDictionary actual.Returns a read-only copy of the current OrderedDictionary collection.

Clear()

Quita todos los elementos de la colección OrderedDictionary.Removes all elements from the OrderedDictionary collection.

Contains(Object)

Determina si la colección OrderedDictionary contiene una clave específica.Determines whether the OrderedDictionary collection contains a specific key.

CopyTo(Array, Int32)

Copia los elementos de la colección OrderedDictionary a un objeto Array unidimensional en el índice especificado.Copies the OrderedDictionary elements to a one-dimensional Array object at the specified index.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

Devuelve un objeto IDictionaryEnumerator que itera por la colección OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa la interfaz ISerializable y devuelve los datos necesarios para serializar la colección OrderedDictionary.Implements the ISerializable interface and returns the data needed to serialize the OrderedDictionary collection.

GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
Insert(Int32, Object, Object)

Inserta una nueva entrada en la colección OrderedDictionary con la clave y el valor especificados en el índice especificado.Inserts a new entry into the OrderedDictionary collection with the specified key and value at the specified index.

MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserialization(Object)

Implementa la interfaz ISerializable. El evento de deserialización vuelve a llamar a este método cuando se completa la deserialización.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

Remove(Object)

Quita la entrada con la clave especificada de la colección OrderedDictionary.Removes the entry with the specified key from the OrderedDictionary collection.

RemoveAt(Int32)

Quita la entrada del índice especificado de la colección OrderedDictionary.Removes the entry at the specified index from the OrderedDictionary collection.

ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ICollection.IsSynchronized

Obtiene un valor que indica si el acceso al objeto OrderedDictionary está sincronizado (es seguro para subprocesos).Gets a value indicating whether access to the OrderedDictionary object is synchronized (thread-safe).

ICollection.SyncRoot

Obtiene un objeto que puede utilizarse para sincronizar el acceso al objeto OrderedDictionary.Gets an object that can be used to synchronize access to the OrderedDictionary object.

IDeserializationCallback.OnDeserialization(Object)

Implementa la interfaz ISerializable. El evento de deserialización vuelve a llamar a este método cuando se completa la deserialización.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

IDictionary.IsFixedSize

Obtiene un valor que indica si la colección OrderedDictionary tiene un tamaño fijo.Gets a value indicating whether the OrderedDictionary has a fixed size.

IEnumerable.GetEnumerator()

Devuelve un objeto IDictionaryEnumerator que itera por la colección OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

Extension Methods

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

Applies to