Dictionary<TKey,TValue> Constructeurs

Définition

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue>.

Surcharges

Dictionary<TKey,TValue>()

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le comparateur d'égalité par défaut pour le type de clé.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié et utilise le comparateur d'égalité par défaut pour le type de clé.

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés à partir du IEnumerable<T> spécifié.

Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IEqualityComparer<T> spécifié.

Dictionary<TKey,TValue>(Int32)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le comparateur d'égalité par défaut pour le type de clé.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés de IDictionary<TKey,TValue> et utilise le IEqualityComparer<T> spécifié.

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés de IEnumerable<T> et utilise le IEqualityComparer<T> spécifié.

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IEqualityComparer<T> spécifié.

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
Obsolète.

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> avec des données sérialisées.

Dictionary<TKey,TValue>()

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le comparateur d'égalité par défaut pour le type de clé.

public:
 Dictionary();
public Dictionary ();
Public Sub New ()

Exemples

L’exemple de code suivant crée un vide Dictionary<TKey,TValue> de chaînes avec des clés de chaîne et utilise la Add méthode pour ajouter des éléments. L’exemple montre que la Add méthode lève un ArgumentException lors de la tentative d’ajout d’une clé en double.

Cet exemple de code fait partie d’un exemple plus grand fourni pour la Dictionary<TKey,TValue> classe .

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew Dictionary<String^, String^>();

// Add some elements to the dictionary. 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 dictionary.
try
{
    openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
    Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<string, string>();

// Add some elements to the dictionary. 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 dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)

' Add some elements to the dictionary. 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 dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

Remarques

Chaque clé d’un Dictionary<TKey,TValue> doit être unique en fonction du comparateur d’égalité par défaut.

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation. Vous pouvez également spécifier une implémentation de l’interface générique à l’aide IEqualityComparer<T> d’un constructeur qui accepte un comparer paramètre.

Notes

Si vous pouvez estimer la taille de la collection, l’utilisation d’un constructeur qui spécifie la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au Dictionary<TKey,TValue>.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié et utilise le comparateur d'égalité par défaut pour le type de clé.

public:
 Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary);
public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue))

Paramètres

dictionary
IDictionary<TKey,TValue>

IDictionary<TKey,TValue> dont les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.

Exceptions

dictionary est null.

dictionary contient une ou plusieurs clés en double.

Exemples

L’exemple de code suivant montre comment utiliser le Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructeur pour initialiser un avec du contenu trié à partir d’un Dictionary<TKey,TValue> autre dictionnaire. L’exemple de code crée un SortedDictionary<TKey,TValue> et le remplit avec des données dans un ordre aléatoire, puis passe le SortedDictionary<TKey,TValue> au Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructeur, créant un Dictionary<TKey,TValue> tri trié. Cela est utile si vous devez créer un dictionnaire trié qui, à un moment donné, devient statique ; la copie des données d’un SortedDictionary<TKey,TValue> vers un Dictionary<TKey,TValue> améliore la vitesse de récupération.

using System;
using System.Collections.Generic;

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

        // Add some elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Create a Dictionary of strings with string keys, and
        // initialize it with the contents of the sorted dictionary.
        Dictionary<string, string> copy =
            new Dictionary<string, string>(openWith);

        // List the contents of the copy.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in copy )
        {
            Console.WriteLine("Key = {0}, Value = {1}",
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted dictionary of strings, with string 
        ' keys.
        Dim openWith As New SortedDictionary(Of String, String)
        
        ' Add some elements to the sorted dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' Create a Dictionary of strings with string keys, and 
        ' initialize it with the contents of the sorted dictionary.
        Dim copy As New Dictionary(Of String, String)(openWith)

        ' List the contents of the copy.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In copy
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Remarques

Chaque clé d’un Dictionary<TKey,TValue> doit être unique selon le comparateur d’égalité par défaut ; de même, chaque clé de la source dictionary doit également être unique selon le comparateur d’égalité par défaut.

La capacité initiale du nouveau Dictionary<TKey,TValue> est suffisamment grande pour contenir tous les éléments dans dictionary.

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation. Vous pouvez également spécifier une implémentation de l’interface générique à l’aide IEqualityComparer<T> d’un constructeur qui accepte un comparer paramètre.

Ce constructeur est une opération O(n), où n est le nombre d’éléments dans dictionary.

Voir aussi

S’applique à

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés à partir du IEnumerable<T> spécifié.

public:
 Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection);
public Dictionary (System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)))

Paramètres

collection
IEnumerable<KeyValuePair<TKey,TValue>>

IEnumerable<T> dont les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.

Exceptions

collection est null.

collection contient une ou plusieurs clés en double.

S’applique à

Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IEqualityComparer<T> spécifié.

public:
 Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary (System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (comparer As IEqualityComparer(Of TKey))

Paramètres

comparer
IEqualityComparer<TKey>

Implémentation de IEqualityComparer<T> à utiliser pendant la comparaison de clés, ou null pour utiliser le EqualityComparer<T> par défaut pour le type de la clé.

Exemples

L’exemple de code suivant crée un Dictionary<TKey,TValue> avec un comparateur d’égalité respectant la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des touches minuscules et d’autres avec des touches majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par la casse, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments dans le dictionnaire.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new Dictionary of strings, with string keys
        // and a case-insensitive comparer for the current culture.
        Dictionary<string, string> openWith =
                      new Dictionary<string, string>(
                          StringComparer.CurrentCultureIgnoreCase);

        // Add some elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Try to add a fifth element with a key that is the same
        // except for case; this would be allowed with the default
        // comparer.
        try
        {
            openWith.Add("BMP", "paint.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("\nBMP is already in the dictionary.");
        }

        // List the contents of the sorted dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
                kvp.Value);
        }
    }
}

/* This code example produces the following output:

BMP is already in the dictionary.

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new Dictionary of strings, with string keys 
        ' and a case-insensitive comparer for the current culture.
        Dim openWith As New Dictionary(Of String, String)( _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add some elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' Try to add a fifth element with a key that is the same 
        ' except for case; this would be allowed with the default
        ' comparer.
        Try
            openWith.Add("BMP", "paint.exe")
        Catch ex As ArgumentException
            Console.WriteLine(vbLf & "BMP is already in the dictionary.")
        End Try
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe

Remarques

Utilisez ce constructeur avec les comparateurs de chaînes insensibles à la casse fournis par la StringComparer classe pour créer des dictionnaires avec des clés de chaîne insensibles à la casse.

Chaque clé d’un Dictionary<TKey,TValue> doit être unique en fonction du comparateur spécifié.

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Si comparer est null, ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation.

Notes

Si vous pouvez estimer la taille de la collection, l’utilisation d’un constructeur qui spécifie la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au Dictionary<TKey,TValue>.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

Dictionary<TKey,TValue>(Int32)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le comparateur d'égalité par défaut pour le type de clé.

public:
 Dictionary(int capacity);
public Dictionary (int capacity);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer)

Paramètres

capacity
Int32

Nombre initial d'éléments que Dictionary<TKey,TValue> peut contenir.

Exceptions

capacity est inférieur à 0.

Exemples

L’exemple de code suivant crée un dictionnaire avec une capacité initiale de 4 et le remplit avec 4 entrées.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys and
        // an initial capacity of 4.
        Dictionary<string, string> openWith =
                               new Dictionary<string, string>(4);

        // Add 4 elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // List the contents of the dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}",
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys and
        ' an initial capacity of 4.
        Dim openWith As New Dictionary(Of String, String)(4)
        
        ' Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe

Remarques

Chaque clé d’un Dictionary<TKey,TValue> doit être unique en fonction du comparateur d’égalité par défaut.

La capacité d’un Dictionary<TKey,TValue> correspond au nombre d’éléments qui peuvent être ajoutés au avant que le Dictionary<TKey,TValue> redimensionnement ne soit nécessaire. À mesure que des éléments sont ajoutés à un Dictionary<TKey,TValue>, la capacité est automatiquement augmentée en fonction des besoins en réaffectant le tableau interne.

Si la taille de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation. Vous pouvez également spécifier une implémentation de l’interface générique à l’aide IEqualityComparer<T> d’un constructeur qui accepte un comparer paramètre.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés de IDictionary<TKey,TValue> et utilise le IEqualityComparer<T> spécifié.

public:
 Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IEqualityComparer(Of TKey))

Paramètres

dictionary
IDictionary<TKey,TValue>

IDictionary<TKey,TValue> dont les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

Implémentation de IEqualityComparer<T> à utiliser pendant la comparaison de clés, ou null pour utiliser le EqualityComparer<T> par défaut pour le type de la clé.

Exceptions

dictionary est null.

dictionary contient une ou plusieurs clés en double.

Exemples

L’exemple de code suivant montre comment utiliser le Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructeur pour initialiser un avec un Dictionary<TKey,TValue> contenu trié sans respect de la casse à partir d’un autre dictionnaire. L’exemple de code crée un SortedDictionary<TKey,TValue> avec un comparateur qui ne respecte pas la casse et le remplit avec des données dans un ordre aléatoire, puis passe le SortedDictionary<TKey,TValue> au Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructeur, ainsi qu’un comparateur d’égalité respectant la casse, créant un Dictionary<TKey,TValue> trié. Cela est utile si vous devez créer un dictionnaire trié qui, à un moment donné, devient statique ; la copie des données d’un SortedDictionary<TKey,TValue> vers un Dictionary<TKey,TValue> améliore la vitesse de récupération.

Notes

Lorsque vous créez un dictionnaire avec un comparateur non respectant la casse et que vous le remplissez avec des entrées d’un dictionnaire qui utilise un comparateur respectant la casse, comme dans cet exemple, une exception se produit si le dictionnaire d’entrée a des clés qui diffèrent uniquement par la casse.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted dictionary of strings, with string
        // keys and a case-insensitive comparer.
        SortedDictionary<string, string> openWith =
                new SortedDictionary<string, string>(
                    StringComparer.CurrentCultureIgnoreCase);

        // Add some elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("Bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Create a Dictionary of strings with string keys and a
        // case-insensitive equality comparer, and initialize it
        // with the contents of the sorted dictionary.
        Dictionary<string, string> copy =
                new Dictionary<string, string>(openWith,
                    StringComparer.CurrentCultureIgnoreCase);

        // List the contents of the copy.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in copy )
        {
            Console.WriteLine("Key = {0}, Value = {1}",
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = Bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted dictionary of strings, with string 
        ' keys and a case-insensitive comparer.
        Dim openWith As New SortedDictionary(Of String, String)( _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add some elements to the sorted dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("Bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' Create a Dictionary of strings with string keys and a 
        ' case-insensitive equality comparer, and initialize it
        ' with the contents of the sorted dictionary.
        Dim copy As New Dictionary(Of String, String)(openWith, _
            StringComparer.CurrentCultureIgnoreCase)

        ' List the contents of the copy.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In copy
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Remarques

Utilisez ce constructeur avec les comparateurs de chaînes insensibles à la casse fournis par la StringComparer classe pour créer des dictionnaires avec des clés de chaîne insensibles à la casse.

Chaque clé d’un Dictionary<TKey,TValue> doit être unique en fonction du comparateur spécifié ; de même, chaque clé de la source dictionary doit également être unique en fonction du comparateur spécifié.

Notes

Par exemple, des clés en double peuvent se produire si comparer est l’un des comparateurs de chaînes non respectant la casse fournis par la StringComparer classe et dictionary n’utilise pas de clé de comparaison sans respect de la casse.

La capacité initiale du nouveau Dictionary<TKey,TValue> est suffisamment grande pour contenir tous les éléments dans dictionary.

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Si comparer est null, ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation.

Ce constructeur est une opération O(n), où n est le nombre d’éléments dans dictionary.

Voir aussi

S’applique à

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui contient des éléments copiés de IEnumerable<T> et utilise le IEqualityComparer<T> spécifié.

public:
 Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
public Dictionary (System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)), comparer As IEqualityComparer(Of TKey))

Paramètres

collection
IEnumerable<KeyValuePair<TKey,TValue>>

IEnumerable<T> dont les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

Implémentation de IEqualityComparer<T> à utiliser pendant la comparaison de clés, ou null pour utiliser le EqualityComparer<T> par défaut pour le type de la clé.

Exceptions

collection est null.

collection contient une ou plusieurs clés en double.

S’applique à

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IEqualityComparer<T> spécifié.

public:
 Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary (int capacity, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of TKey))

Paramètres

capacity
Int32

Nombre initial d'éléments que Dictionary<TKey,TValue> peut contenir.

comparer
IEqualityComparer<TKey>

Implémentation de IEqualityComparer<T> à utiliser pendant la comparaison de clés, ou null pour utiliser le EqualityComparer<T> par défaut pour le type de la clé.

Exceptions

capacity est inférieur à 0.

Exemples

L’exemple de code suivant crée un Dictionary<TKey,TValue> avec une capacité initiale de 5 et un comparateur d’égalité ne respectant pas la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des touches minuscules et d’autres avec des clés majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par la casse, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments dans le dictionnaire.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys, an
        // initial capacity of 5, and a case-insensitive equality
        // comparer.
        Dictionary<string, string> openWith =
                      new Dictionary<string, string>(5,
                          StringComparer.CurrentCultureIgnoreCase);

        // Add 4 elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Try to add a fifth element with a key that is the same
        // except for case; this would be allowed with the default
        // comparer.
        try
        {
            openWith.Add("BMP", "paint.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("\nBMP is already in the dictionary.");
        }

        // List the contents of the dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
                kvp.Value);
        }
    }
}

/* This code example produces the following output:

BMP is already in the dictionary.

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new Dictionary of strings, with string keys, an
        ' initial capacity of 5, and a case-insensitive equality
        ' comparer.
        Dim openWith As New Dictionary(Of String, String)(5, _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' Try to add a fifth element with a key that is the same 
        ' except for case; this would be allowed with the default
        ' comparer.
        Try
            openWith.Add("BMP", "paint.exe")
        Catch ex As ArgumentException
            Console.WriteLine(vbLf & "BMP is already in the dictionary.")
        End Try
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe

Remarques

Utilisez ce constructeur avec les comparateurs de chaînes ne respectant pas la casse fournis par la StringComparer classe pour créer des dictionnaires avec des clés de chaîne ne respectant pas la casse.

Chaque clé d’un Dictionary<TKey,TValue> doit être unique en fonction du comparateur spécifié.

La capacité d’un Dictionary<TKey,TValue> est le nombre d’éléments qui peuvent être ajoutés à avant que le Dictionary<TKey,TValue> redimensionnement ne soit nécessaire. À mesure que des éléments sont ajoutés à un Dictionary<TKey,TValue>, la capacité est automatiquement augmentée en fonction des besoins en réaffectant le tableau interne.

Si la taille de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement lors de l’ajout Dictionary<TKey,TValue>d’éléments au .

Dictionary<TKey,TValue> nécessite une implémentation d’égalité pour déterminer si les clés sont égales. Si comparer a la valeur null, ce constructeur utilise le comparateur d’égalité générique par défaut, EqualityComparer<T>.Default. Si type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Attention

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

Initialise une nouvelle instance de la classe Dictionary<TKey,TValue> avec des données sérialisées.

protected:
 Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Dictionary (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Dictionary (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Paramètres

info
SerializationInfo

Objet SerializationInfo contenant les informations nécessaires pour sérialiser Dictionary<TKey,TValue>.

context
StreamingContext

Structure StreamingContext contenant la source et la destination du flux sérialisé associé à Dictionary<TKey,TValue>.

Attributs

Remarques

Ce constructeur est appelé lors de la désérialisation pour reconstituer un objet transmis sur un flux. Pour plus d’informations, consultez Sérialisation XML et SOAP.

Voir aussi

S’applique à