Dictionary<TKey,TValue> Constructeurs
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Initialise une nouvelle instance de la classe Dictionary<TKey,TValue>.
Surcharges
| Nom | Description |
|---|---|
| Dictionary<TKey,TValue>() |
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a 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 Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément 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 Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du fichier spécifié IEnumerable<T>. |
| Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a la capacité initiale par défaut et utilise la valeur spécifiée IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32) |
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a 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 Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du spécifié IDictionary<TKey,TValue> et utilise le fichier spécifié IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) |
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du spécifié IEnumerable<T> et utilise le fichier spécifié IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a la capacité initiale spécifiée et utilise la valeur spécifiée IEqualityComparer<T>. |
| 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
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a 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 une chaîne vide Dictionary<TKey,TValue> 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 une ArgumentException exception 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 =
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.
let openWith = 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")
with :? ArgumentException ->
printfn "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 le 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.
Note
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 lors de l’ajout Dictionary<TKey,TValue>d’éléments au .
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
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément 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>
Dont IDictionary<TKey,TValue> les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.
Exceptions
dictionary a la valeur null.
dictionary contient une ou plusieurs clés dupliquées.
Exemples
L’exemple de code suivant montre comment utiliser le Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructeur pour initialiser un Dictionary<TKey,TValue> contenu trié à partir d’un autre dictionnaire. L’exemple de code crée et SortedDictionary<TKey,TValue> le remplit avec des données dans l’ordre aléatoire, puis passe le Dictionary<TKey,TValue>(IEqualityComparer<TKey>)SortedDictionary<TKey,TValue> constructeur, créant ainsi un Dictionary<TKey,TValue> tri trié. Cela est utile si vous devez créer un dictionnaire trié qui devient statique à un moment donné ; La copie des données d’un SortedDictionary<TKey,TValue> vers une Dictionary<TKey,TValue> vitesse de récupération 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
*/
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys.
let openWith = 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.
let copy = Dictionary<string, string> openWith
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {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 en fonction du comparateur d’égalité par défaut ; de même, chaque clé de la source dictionary doit également être unique en fonction du 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 le 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
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du fichier spécifié IEnumerable<T>.
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>>
Dont IEnumerable<T> les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.
Exceptions
collection a la valeur null.
collection contient une ou plusieurs clés dupliquées.
S’applique à
Dictionary<TKey,TValue>(IEqualityComparer<TKey>)
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a la capacité initiale par défaut et utilise la valeur spécifiée IEqualityComparer<T>.
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 IEqualityComparer<T> à utiliser lors de la comparaison des clés ou null pour utiliser la valeur par défaut EqualityComparer<T> pour le type de la clé.
Exemples
L’exemple de code suivant crée un Dictionary<TKey,TValue> comparateur d’égalité respectant la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des clés minuscules et certains 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 cas, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments du 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
*/
open System
open System.Collections.Generic
// Create a new Dictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
let openWith = 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")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the sorted dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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 ne respectant pas la casse fournis par la classe pour créer des dictionnaires avec des clés de chaîne non sensibles à la StringComparer 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 c’est nullle cas, ce constructeur utilise le comparateur d’égalité générique par défaut. EqualityComparer<T>.Default Si le type TKey implémente l’interface System.IEquatable<T> générique, le comparateur d’égalité par défaut utilise cette implémentation.
Note
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 lors de l’ajout Dictionary<TKey,TValue>d’éléments au .
Ce constructeur est une opération O(1).
Avertissement
Si capacity elle provient de l’entrée utilisateur, préférez utiliser un constructeur sans paramètre de capacité et laisser la collection redimensionner en tant qu’éléments. Si vous devez utiliser une valeur spécifiée par l’utilisateur, limitez-la à une limite raisonnable (par exemple) Math.Clamp(untrustedValue, 0, 20)ou vérifiez que le nombre d’éléments correspond à la valeur spécifiée.
Voir aussi
S’applique à
Dictionary<TKey,TValue>(Int32)
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a 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 le Dictionary<TKey,TValue> conteneur 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
*/
open System.Collections.Generic
// Create a new dictionary of strings, with string keys and
// an initial capacity of 4.
let openWith = 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.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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> est le nombre d’éléments qui peuvent être ajoutés à l’avant que le Dictionary<TKey,TValue> redimensionnement soit nécessaire. À mesure que les éléments sont ajoutés à un Dictionary<TKey,TValue>, la capacité est automatiquement augmentée 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. Ce constructeur utilise le comparateur d’égalité générique par défaut. EqualityComparer<T>.Default Si le 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).
Avertissement
Si capacity elle provient de l’entrée utilisateur, préférez utiliser un constructeur sans paramètre de capacité et laisser la collection redimensionner en tant qu’éléments. Si vous devez utiliser une valeur spécifiée par l’utilisateur, limitez-la à une limite raisonnable (par exemple) Math.Clamp(untrustedValue, 0, 20)ou vérifiez que le nombre d’éléments correspond à la valeur spécifiée.
Voir aussi
S’applique à
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du spécifié IDictionary<TKey,TValue> et utilise le fichier spécifié IEqualityComparer<T>.
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>
Dont IDictionary<TKey,TValue> les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Implémentation IEqualityComparer<T> à utiliser lors de la comparaison des clés ou null pour utiliser la valeur par défaut EqualityComparer<T> pour le type de la clé.
Exceptions
dictionary a la valeur null.
dictionary contient une ou plusieurs clés dupliquées.
Exemples
L’exemple de code suivant montre comment utiliser le constructeur pour initialiser un Dictionary<TKey,TValue> contenu trié sans respect de la Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) casse à partir d’un autre dictionnaire. L’exemple de code crée un SortedDictionary<TKey,TValue> comparateur qui ne respecte pas la casse et le remplit avec des données dans l’ordre aléatoire, puis passe le SortedDictionary<TKey,TValue> constructeur, ainsi qu’un comparateur d’égalité ne respectant pas la Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) casse, créant ainsi un comparateur d’égalité Dictionary<TKey,TValue> qui est trié. Cela est utile si vous devez créer un dictionnaire trié qui devient statique à un moment donné ; La copie des données d’un SortedDictionary<TKey,TValue> vers une Dictionary<TKey,TValue> vitesse de récupération améliore la vitesse de récupération.
Note
Lorsque vous créez un dictionnaire avec un comparateur ne respectant pas la casse et que vous le remplissez avec des entrées d’un dictionnaire qui utilise un comparateur sensible à 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 cas.
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
*/
open System
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys and a case-insensitive comparer.
let openWith =
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.
let copy =
Dictionary<string, string>(openWith, StringComparer.CurrentCultureIgnoreCase)
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {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 ne respectant pas la casse fournis par la classe pour créer des dictionnaires avec des clés de chaîne non sensibles à la StringComparer 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é.
Note
Par exemple, les clés en double peuvent se produire si comparer l’un des comparateurs de chaînes ne respectant pas la casse fournis par la classe et dictionary n’utilise pas de clé de comparateur non sensible à la StringComparer 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 c’est nullle cas, ce constructeur utilise le comparateur d’égalité générique par défaut. EqualityComparer<T>.Default Si le 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 se trouve 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
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe qui contient des éléments copiés à partir du spécifié IEnumerable<T> et utilise le fichier spécifié IEqualityComparer<T>.
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>>
Dont IEnumerable<T> les éléments sont copiés dans le nouveau Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Implémentation IEqualityComparer<T> à utiliser lors de la comparaison des clés ou null pour utiliser la valeur par défaut EqualityComparer<T> pour le type de la clé.
Exceptions
collection a la valeur null.
collection contient une ou plusieurs clés dupliquées.
S’applique à
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
- Source:
- Dictionary.cs
Initialise une nouvelle instance de la Dictionary<TKey,TValue> classe vide, a la capacité initiale spécifiée et utilise la valeur spécifiée IEqualityComparer<T>.
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 le Dictionary<TKey,TValue> conteneur peut contenir.
- comparer
- IEqualityComparer<TKey>
Implémentation IEqualityComparer<T> à utiliser lors de la comparaison des clés ou null pour utiliser la valeur par défaut EqualityComparer<T> pour le type de la clé.
Exceptions
capacity est inférieur à 0.
Exemples
L’exemple de code suivant crée une Dictionary<TKey,TValue> 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 clés minuscules et certains 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 cas, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments du 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
*/
open System
open System.Collections.Generic
// Create a new dictionary of strings, with string keys, an
// initial capacity of 5, and a case-insensitive equality
// comparer.
let openWith =
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")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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 classe pour créer des dictionnaires avec des clés de chaîne non sensibles à la StringComparer 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 à l’avant que le Dictionary<TKey,TValue> redimensionnement soit nécessaire. À mesure que les éléments sont ajoutés à un Dictionary<TKey,TValue>, la capacité est automatiquement augmentée 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 c’est nullle cas, ce constructeur utilise le comparateur d’égalité générique par défaut. EqualityComparer<T>.Default Si le 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
- 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);
[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);
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}")>]
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
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 requises pour sérialiser le Dictionary<TKey,TValue>.
- context
- StreamingContext
Structure StreamingContext contenant la source et la destination du flux sérialisé associé au Dictionary<TKey,TValue>.
- Attributs
Remarques
Ce constructeur est appelé pendant la désérialisation pour rétablir un objet transmis sur un flux. Pour plus d’informations, consultez sérialisation XML et SOAP.