OrderedDictionary Classe

Definição

Representa uma coleção de pares chave/valor que são acessíveis por chave ou í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, 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
type OrderedDictionary = class
    interface IOrderedDictionary
    interface ISerializable
    interface IDeserializationCallback
    interface IDictionary
    interface ICollection
    interface IEnumerable
Public Class OrderedDictionary
Implements IDeserializationCallback, IDictionary, IOrderedDictionary, ISerializable
Herança
OrderedDictionary
Derivado
Atributos
Implementações

Exemplos

O exemplo de código a seguir demonstra a criação, a população e OrderedDictionary a modificação de uma coleção, bem como duas técnicas para exibir o OrderedDictionaryconteúdo do: um Keys usando Values as propriedades e e a outra Criando um enumerador por GetEnumerator meio do método.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)

Comentários

Cada elemento é um par de chave/valor armazenado em DictionaryEntry um objeto.Each element is a key/value pair stored in a DictionaryEntry object. Uma chave não pode nullser, mas um valor pode ser.A key cannot be null, but a value can be.

Os elementos de um OrderedDictionary não são classificados pela chave, ao contrário dos elementos de uma SortedDictionary<TKey,TValue> classe.The elements of an OrderedDictionary are not sorted by the key, unlike the elements of a SortedDictionary<TKey,TValue> class. Você pode acessar elementos pela chave ou pelo índice.You can access elements either by the key or by the index.

A foreach instrução do C# idioma (For Each em Visual Basic) retorna objetos que são do tipo de cada elemento na coleção.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. Como cada elemento da OrderedDictionary coleção é um par chave/valor, o tipo de elemento não é o tipo da chave ou o tipo do 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. Em vez disso, o tipo DictionaryEntryde elemento é.Instead, the element type is DictionaryEntry. O código a seguir C#mostra, Visual Basic C++ e sintaxe.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

A foreach instrução é um wrapper em volta do enumerador, que permite somente a leitura, não a coleção.The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Construtores

OrderedDictionary()

Inicializa uma nova instância da classe OrderedDictionary.Initializes a new instance of the OrderedDictionary class.

OrderedDictionary(IEqualityComparer)

Inicializa uma nova instância da classe OrderedDictionary usando o comparador especificado.Initializes a new instance of the OrderedDictionary class using the specified comparer.

OrderedDictionary(Int32)

Inicializa uma nova instância da classe OrderedDictionary usando a capacidade inicial especificada.Initializes a new instance of the OrderedDictionary class using the specified initial capacity.

OrderedDictionary(Int32, IEqualityComparer)

Inicializa uma nova instância da classe OrderedDictionary usando o comparador e a capacidade inicial especificados.Initializes a new instance of the OrderedDictionary class using the specified initial capacity and comparer.

OrderedDictionary(SerializationInfo, StreamingContext)

Inicializa uma nova instância da classe OrderedDictionary que pode ser serializada usando os objetos SerializationInfo e StreamingContext especificados.Initializes a new instance of the OrderedDictionary class that is serializable using the specified SerializationInfo and StreamingContext objects.

Propriedades

Count

Obtém o número dos pares chave-valor contidos na coleção OrderedDictionary.Gets the number of key/values pairs contained in the OrderedDictionary collection.

IsReadOnly

Obtém um valor que indica se a coleção OrderedDictionary é somente leitura.Gets a value indicating whether the OrderedDictionary collection is read-only.

Item[Int32]

Obtém ou define o valor no índice especificado.Gets or sets the value at the specified index.

Item[Object]

Obtém ou define o valor com a chave especificada.Gets or sets the value with the specified key.

Keys

Define um objeto ICollection que contém as chaves na coleção OrderedDictionary.Gets an ICollection object containing the keys in the OrderedDictionary collection.

Values

Obtém um objeto ICollection que contém os valores na coleção OrderedDictionary.Gets an ICollection object containing the values in the OrderedDictionary collection.

Métodos

Add(Object, Object)

Adiciona uma entrada com a chave e o valor especificados à coleção OrderedDictionary com o índice mais baixo disponível.Adds an entry with the specified key and value into the OrderedDictionary collection with the lowest available index.

AsReadOnly()

Retorna uma cópia somente leitura da coleção OrderedDictionary atual.Returns a read-only copy of the current OrderedDictionary collection.

Clear()

Remove todos os elementos da coleção OrderedDictionary.Removes all elements from the OrderedDictionary collection.

Contains(Object)

Determina se a coleção OrderedDictionary contém uma chave específica.Determines whether the OrderedDictionary collection contains a specific key.

CopyTo(Array, Int32)

Copia os elementos OrderedDictionary para um objeto Array unidimensional no índice especificado.Copies the OrderedDictionary elements to a one-dimensional Array object at the specified index.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetEnumerator()

Retorna um objeto IDictionaryEnumerator que itera na coleção de OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa a interface ISerializable e retorna os dados necessários para serializar a coleção OrderedDictionary.Implements the ISerializable interface and returns the data needed to serialize the OrderedDictionary collection.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Insert(Int32, Object, Object)

Insere uma nova entrada para a coleção OrderedDictionary com a chave especificada e o valor no índice especificado.Inserts a new entry into the OrderedDictionary collection with the specified key and value at the specified index.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
OnDeserialization(Object)

Implementa a interface ISerializable e é chamado novamente pelo evento de desserialização quando a desserialização é concluída.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

Remove(Object)

Remove a entrada com a chave especificada da coleção OrderedDictionary.Removes the entry with the specified key from the OrderedDictionary collection.

RemoveAt(Int32)

Remove a entrada no índice especificado da coleção OrderedDictionary.Removes the entry at the specified index from the OrderedDictionary collection.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Implantações explícitas de interface

ICollection.IsSynchronized

Obtém um valor que indica se o acesso ao objeto OrderedDictionary é sincronizado (thread-safe).Gets a value indicating whether access to the OrderedDictionary object is synchronized (thread-safe).

ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao objeto OrderedDictionary.Gets an object that can be used to synchronize access to the OrderedDictionary object.

IDeserializationCallback.OnDeserialization(Object)

Implementa a interface ISerializable e é chamado novamente pelo evento de desserialização quando a desserialização é concluída.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

IDictionary.IsFixedSize

Obtém um valor que indica se o OrderedDictionary tem um tamanho fixo.Gets a value indicating whether the OrderedDictionary has a fixed size.

IEnumerable.GetEnumerator()

Retorna um objeto IDictionaryEnumerator que itera na coleção de OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable.

Aplica-se a