OrderedDictionary Classe

Definição

Representa uma coleção de pares chave/valor acessíveis pela chave ou índice.

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
[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
[<System.Serializable>]
type OrderedDictionary = class
    interface IOrderedDictionary
    interface IDictionary
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
type OrderedDictionary = class
    interface ICollection
    interface IEnumerable
    interface IDictionary
    interface IOrderedDictionary
    interface IDeserializationCallback
    interface ISerializable
Public Class OrderedDictionary
Implements IDictionary, IOrderedDictionary
Public Class OrderedDictionary
Implements IDeserializationCallback, IDictionary, IOrderedDictionary, ISerializable
Public Class OrderedDictionary
Implements IDeserializationCallback, IOrderedDictionary, ISerializable
Herança
OrderedDictionary
Derivado
Atributos
Implementações

Exemplos

O seguinte exemplo de código demonstra a criação, população e modificação de uma OrderedDictionary coleção, bem como duas técnicas para exibir o conteúdo do OrderedDictionary: uma usando as Keys propriedades e Values a outra criando um enumerador através do GetEnumerator método.

// 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);
    }

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

Observações

Cada elemento é um par chave/valor armazenado num DictionaryEntry objeto. Uma chave não pode ser null, mas um valor pode ser.

Os elementos de um OrderedDictionary não estão ordenados pela chave, ao contrário dos elementos de uma SortedDictionary<TKey,TValue> classe. Pode aceder a elementos quer pela chave, quer pelo índice.

A instrução foreach da linguagem C# (For Each em Visual Basic) devolve objetos do tipo de cada elemento na coleção. Como cada elemento da OrderedDictionary coleção é um par chave/valor, o tipo de elemento não é o tipo da chave nem o tipo do valor. Em vez disso, o tipo de elemento é DictionaryEntry. O código seguinte mostra a sintaxe.

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

A foreach declaração é um wrapper em torno do enumerador, que só permite ler a partir da coleção, não escrever para.

Construtores

Name Description
OrderedDictionary()

Inicializa uma nova instância da OrderedDictionary classe.

OrderedDictionary(IEqualityComparer)

Inicializa uma nova instância da OrderedDictionary classe usando o comparador especificado.

OrderedDictionary(Int32, IEqualityComparer)

Inicializa uma nova instância da OrderedDictionary classe usando a capacidade inicial e o comparador especificados.

OrderedDictionary(Int32)

Inicializa uma nova instância da OrderedDictionary classe usando a capacidade inicial especificada.

OrderedDictionary(SerializationInfo, StreamingContext)

Inicializa uma nova instância da OrderedDictionary classe que é serializável usando os objetos e StreamingContext especificadosSerializationInfo.

Propriedades

Name Description
Count

Obtém o número de pares chave/valores contidos na OrderedDictionary coleção.

IsReadOnly

Recebe um valor que indica se a OrderedDictionary coleção é apenas de leitura.

Item[Int32]

Obtém ou define o valor no índice especificado.

Item[Object]

Recebe ou define o valor com a chave especificada.

Keys

Obtém um ICollection objeto contendo as chaves na OrderedDictionary coleção.

Values

Obtém um ICollection objeto contendo os valores da OrderedDictionary coleção.

Métodos

Name Description
Add(Object, Object)

Adiciona uma entrada com a chave e valor especificados à OrderedDictionary coleção com o índice mais baixo disponível.

AsReadOnly()

Devolve uma cópia apenas de leitura da coleção atual OrderedDictionary .

Clear()

Remove todos os elementos da OrderedDictionary coleção.

Contains(Object)

Determina se a OrderedDictionary coleção contém uma chave específica.

CopyTo(Array, Int32)

Copia os OrderedDictionary elementos para um objeto unidimensional Array no índice especificado.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Devolve um IDictionaryEnumerator objeto que itera pela OrderedDictionary coleção.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa a ISerializable interface e devolve os dados necessários para serializar a OrderedDictionary coleção.

GetType()

Obtém o Type da instância atual.

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

Insere uma nova entrada na OrderedDictionary coleção com a chave e valor especificados no índice especificado.

MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
OnDeserialization(Object)

Implementa a ISerializable interface e é chamada de volta pelo evento de desserialização quando a desserialização está concluída.

Remove(Object)

Remove a entrada com a chave especificada da OrderedDictionary coleção.

RemoveAt(Int32)

Remove a entrada no índice especificado da OrderedDictionary coleção.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

Name Description
ICollection.IsSynchronized

Recebe um valor que indica se o acesso ao OrderedDictionary objeto está sincronizado (thread-safe).

ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao OrderedDictionary objeto.

IDeserializationCallback.OnDeserialization(Object)

Implementa a ISerializable interface e é chamada de volta pelo evento de desserialização quando a desserialização está concluída.

IDictionary.IsFixedSize

Obtém um valor que indica se o OrderedDictionary tem um tamanho fixo.

IEnumerable.GetEnumerator()

Devolve um IDictionaryEnumerator objeto que itera pela OrderedDictionary coleção.

Métodos da Extensão

Name Description
AsParallel(IEnumerable)

Permite a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable para um IQueryable.

Cast<TResult>(IEnumerable)

Conjura os elementos de an IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base num tipo especificado.

Aplica-se a