OrderedDictionary Classe

Définition

Représente une collection de paires clé/valeur qui sont accessibles par la clé ou l'index.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
Héritage
OrderedDictionary
Dérivé
Attributs
Implémente

Exemples

L’exemple de code suivant illustre la création, le remplissage et la OrderedDictionary modification d’une collection, ainsi que deux techniques permettant d’afficher le OrderedDictionarycontenu de: un Keys à Values l’aide des propriétés et et l’autre création d’un énumérateur à GetEnumerator l’aide de la méthode.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)

Remarques

Chaque élément est une paire clé/valeur stockée dans DictionaryEntry un objet.Each element is a key/value pair stored in a DictionaryEntry object. Une clé ne peut nullpas être, mais une valeur peut être.A key cannot be null, but a value can be.

Les éléments d’un OrderedDictionary ne sont pas triés par clé, contrairement aux éléments d' SortedDictionary<TKey,TValue> une classe.The elements of an OrderedDictionary are not sorted by the key, unlike the elements of a SortedDictionary<TKey,TValue> class. Vous pouvez accéder aux éléments soit par la clé, soit par l’index.You can access elements either by the key or by the index.

L' foreach instruction de la C# langue (For Each en Visual Basic) retourne des objets qui sont du type de chaque élément de la collection.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. Étant donné que chaque élément OrderedDictionary de la collection est une paire clé/valeur, le type d’élément n’est pas le type de la clé ou le type de la valeur.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. Au lieu de cela, le DictionaryEntrytype d’élément est.Instead, the element type is DictionaryEntry. Le code suivant illustre C#Visual Basic et C++ la syntaxe.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

L' foreach instruction est un wrapper autour de l’énumérateur, qui autorise uniquement la lecture, et non l’écriture, de la collection.The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Constructeurs

OrderedDictionary()

Initialise une nouvelle instance de la classe OrderedDictionary.Initializes a new instance of the OrderedDictionary class.

OrderedDictionary(IEqualityComparer)

Initialise une nouvelle instance de la classe OrderedDictionary à l'aide du comparateur spécifié.Initializes a new instance of the OrderedDictionary class using the specified comparer.

OrderedDictionary(Int32)

Initialise une nouvelle instance de la classe OrderedDictionary à l'aide de la capacité initiale spécifiée.Initializes a new instance of the OrderedDictionary class using the specified initial capacity.

OrderedDictionary(Int32, IEqualityComparer)

Initialise une nouvelle instance de la classe OrderedDictionary à l'aide de la capacité initiale et du comparateur spécifiés.Initializes a new instance of the OrderedDictionary class using the specified initial capacity and comparer.

OrderedDictionary(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe OrderedDictionary qui est sérialisable à l'aide des objets SerializationInfo et StreamingContext spécifiés.Initializes a new instance of the OrderedDictionary class that is serializable using the specified SerializationInfo and StreamingContext objects.

Propriétés

Count

Obtient le nombre de paires clé/valeur contenues dans la collection OrderedDictionary.Gets the number of key/values pairs contained in the OrderedDictionary collection.

IsReadOnly

Obtient une valeur indiquant si la collection OrderedDictionary est en lecture seule.Gets a value indicating whether the OrderedDictionary collection is read-only.

Item[Int32]

Obtient ou définit la valeur à l'index spécifié.Gets or sets the value at the specified index.

Item[Object]

Obtient ou définit la valeur avec la clé spécifiée.Gets or sets the value with the specified key.

Keys

Obtient un objet ICollection contenant les clés de la collection OrderedDictionary.Gets an ICollection object containing the keys in the OrderedDictionary collection.

Values

Obtient un objet ICollection contenant les valeurs de la collection OrderedDictionary.Gets an ICollection object containing the values in the OrderedDictionary collection.

Méthodes

Add(Object, Object)

Ajoute une entrée avec la clé et la valeur spécifiées dans la collection OrderedDictionary avec l'index disponible le plus bas.Adds an entry with the specified key and value into the OrderedDictionary collection with the lowest available index.

AsReadOnly()

Retourne une copie en lecture seule de la collection OrderedDictionary en cours.Returns a read-only copy of the current OrderedDictionary collection.

Clear()

Supprime tous les éléments de la collection OrderedDictionary.Removes all elements from the OrderedDictionary collection.

Contains(Object)

Détermine si la collection OrderedDictionary contient une clé spécifique.Determines whether the OrderedDictionary collection contains a specific key.

CopyTo(Array, Int32)

Copie les éléments OrderedDictionary dans un objet Array à une dimension à l'index spécifié.Copies the OrderedDictionary elements to a one-dimensional Array object at the specified index.

Equals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.Determines whether the specified object is equal to the current object.

(Hérité de Object)
GetEnumerator()

Retourne un objet IDictionaryEnumerator qui itère au sein de la collection OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

GetHashCode()

Fait office de fonction de hachage par défaut.Serves as the default hash function.

(Hérité de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implémente l'interface ISerializable et retourne les données requises pour sérialiser la collection OrderedDictionary.Implements the ISerializable interface and returns the data needed to serialize the OrderedDictionary collection.

GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Hérité de Object)
Insert(Int32, Object, Object)

Insère une nouvelle entrée dans la collection OrderedDictionary avec la clé et la valeur spécifiées à l'index spécifié.Inserts a new entry into the OrderedDictionary collection with the specified key and value at the specified index.

MemberwiseClone()

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

(Hérité de Object)
OnDeserialization(Object)

Implémente l’interface ISerializable et est rappelé par l’événement de désérialisation quand la désérialisation est terminée.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

Remove(Object)

Supprime l'entrée par la clé spécifiée provenant de la collection OrderedDictionary.Removes the entry with the specified key from the OrderedDictionary collection.

RemoveAt(Int32)

Supprime de la collection l'entrée OrderedDictionary à l'index spécifié.Removes the entry at the specified index from the OrderedDictionary collection.

ToString()

Retourne une chaîne qui représente l'objet actuel.Returns a string that represents the current object.

(Hérité de Object)

Implémentations d’interfaces explicites

ICollection.IsSynchronized

Obtient une valeur indiquant si l'accès à l'objet OrderedDictionary est synchronisé (thread-safe).Gets a value indicating whether access to the OrderedDictionary object is synchronized (thread-safe).

ICollection.SyncRoot

Obtient un objet qui peut être utilisé pour synchroniser l’accès à l’objet OrderedDictionary.Gets an object that can be used to synchronize access to the OrderedDictionary object.

IDeserializationCallback.OnDeserialization(Object)

Implémente l’interface ISerializable et est rappelé par l’événement de désérialisation quand la désérialisation est terminée.Implements the ISerializable interface and is called back by the deserialization event when deserialization is complete.

IDictionary.IsFixedSize

Obtient une valeur indiquant si OrderedDictionary est de taille fixe.Gets a value indicating whether the OrderedDictionary has a fixed size.

IEnumerable.GetEnumerator()

Retourne un objet IDictionaryEnumerator qui itère au sein de la collection OrderedDictionary.Returns an IDictionaryEnumerator object that iterates through the OrderedDictionary collection.

Méthodes d’extension

Cast<TResult>(IEnumerable)

Effectue un cast des éléments d'un IEnumerable vers le type spécifié.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtre les éléments d'un IEnumerable en fonction du type spécifié.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Active la parallélisation d'une requête.Enables parallelization of a query.

AsQueryable(IEnumerable)

Convertit un IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

S’applique à