Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Constructors

Definición

Sobrecargas

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial predeterminada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que contiene los elementos copiados de la interfaz IDictionary<TKey,TValue> especificada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the default equality comparer for the key type.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial predeterminada y utiliza la interfaz IEqualityComparer<T> especificada.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial especificada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que contiene los elementos copiados de la interfaz IDictionary<TKey,TValue> especificada y utiliza la interfaz IEqualityComparer<T> especificada.Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified IEqualityComparer<T>.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial especificada y utiliza el IEqualityComparer<T> especificado.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> con datos serializados.Initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial predeterminada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

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

Ejemplos

En el ejemplo de código siguiente se crea vacío Dictionary<TKey,TValue> de cadenas con claves de cadena y usa el Add método para agregar algunos elementos.The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. El ejemplo muestra que el Add método produce una ArgumentException al intentar agregar una clave duplicada.The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

Este ejemplo de código forma parte de un ejemplo más extenso proporcionado para el Dictionary<TKey,TValue> clase.This code example is part of a larger example provided for the Dictionary<TKey,TValue> class.

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

Comentarios

Todas las claves de un Dictionary<TKey,TValue> deben ser únicos según el comparador de igualdad predeterminado.Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.This constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation. Como alternativa, puede especificar una implementación de la IEqualityComparer<T> interfaz genérica mediante un constructor que acepta un comparer parámetro.Alternatively, you can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter.

Nota

Si puede calcular el tamaño de la colección, utilizando un constructor que especifica la capacidad inicial, elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a la Dictionary<TKey,TValue>.If you can estimate the size of the collection, using a constructor that specifies the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

Este constructor es una operación o (1).This constructor is an O(1) operation.

Consulte también:

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que contiene los elementos copiados de la interfaz IDictionary<TKey,TValue> especificada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the default equality comparer for the key type.

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

Parámetros

Excepciones

El valor de dictionary es null.dictionary is null.

dictionary contiene una o varias claves duplicadas.dictionary contains one or more duplicate keys.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar el Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor para inicializar un Dictionary<TKey,TValue> con ordena el contenido de otro diccionario.The following code example shows how to use the Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor to initialize a Dictionary<TKey,TValue> with sorted content from another dictionary. El ejemplo de código se crea un SortedDictionary<TKey,TValue> y lo rellena con datos en orden aleatorio, a continuación, pasa el SortedDictionary<TKey,TValue> a la Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor, creando un Dictionary<TKey,TValue> que se ordena.The code example creates a SortedDictionary<TKey,TValue> and populates it with data in random order, then passes the SortedDictionary<TKey,TValue> to the Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor, creating a Dictionary<TKey,TValue> that is sorted. Esto es útil si necesita crear un diccionario ordenado que en algún momento se convierte en estático; copiar los datos desde un SortedDictionary<TKey,TValue> a un Dictionary<TKey,TValue> mejora la velocidad de recuperación.This is useful if you need to build a sorted dictionary that at some point becomes static; copying the data from a SortedDictionary<TKey,TValue> to a Dictionary<TKey,TValue> improves retrieval speed.

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

Comentarios

Todas las claves de un Dictionary<TKey,TValue> debe ser única según el valor predeterminado el comparador de igualdad; del mismo modo, todas las claves en el origen de dictionary también deben ser únicos según el comparador de igualdad predeterminado.Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer; likewise, every key in the source dictionary must also be unique according to the default equality comparer.

La capacidad inicial del nuevo Dictionary<TKey,TValue> es lo suficientemente grande como para contener todos los elementos de dictionary.The initial capacity of the new Dictionary<TKey,TValue> is large enough to contain all the elements in dictionary.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.This constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation. Como alternativa, puede especificar una implementación de la IEqualityComparer<T> interfaz genérica mediante un constructor que acepta un comparer parámetro.Alternatively, you can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter.

Este constructor es una operación o (n), donde n es el número de elementos de dictionary.This constructor is an O(n) operation, where n is the number of elements in dictionary.

Consulte también:

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

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

Parámetros

collection
IEnumerable<KeyValuePair<TKey,TValue>>

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial predeterminada y utiliza la interfaz IEqualityComparer<T> especificada.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>.

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

Parámetros

comparer
IEqualityComparer<TKey>

Implementación de IEqualityComparer<T> que se va a utilizar para comparar claves o null si se va a utilizar el EqualityComparer<T> predeterminado para el tipo de la clave.The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

Ejemplos

En el ejemplo de código siguiente se crea un Dictionary<TKey,TValue> con un comparador de igualdad entre mayúsculas y minúsculas para la referencia cultural actual.The following code example creates a Dictionary<TKey,TValue> with a case-insensitive equality comparer for the current culture. El ejemplo agrega cuatro elementos, algunos con claves en minúsculas y otros con claves en mayúsculas.The example adds four elements, some with lower-case keys and some with upper-case keys. El ejemplo se intenta agregar un elemento con una clave que difiere de una clave existente solo por caso, detecta la excepción resultante y muestra un mensaje de error.The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. Por último, el ejemplo muestra los elementos del diccionario.Finally, the example displays the elements in the dictionary.

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

Comentarios

Utilice este constructor con los comparadores de mayúsculas y minúsculas de cadena proporcionados por el StringComparer clase para crear diccionarios con claves de cadena de mayúsculas y minúsculas.Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

Todas las claves de un Dictionary<TKey,TValue> debe ser única según el comparador especificado.Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Si comparer es null, este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

Nota

Si puede calcular el tamaño de la colección, utilizando un constructor que especifica la capacidad inicial, elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a la Dictionary<TKey,TValue>.If you can estimate the size of the collection, using a constructor that specifies the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

Este constructor es una operación o (1).This constructor is an O(1) operation.

Consulte también:

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial especificada y utiliza el comparador de igualdad predeterminado para el tipo de clave.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.

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)

Parámetros

capacity
Int32 Int32 Int32 Int32

Número inicial de elementos que puede contener la colección Dictionary<TKey,TValue>.The initial number of elements that the Dictionary<TKey,TValue> can contain.

Excepciones

Ejemplos

En el ejemplo de código siguiente se crea un diccionario con una capacidad inicial de 4 y lo rellena con 4 entradas.The following code example creates a dictionary with an initial capacity of 4 and populates it with 4 entries.

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

Comentarios

Todas las claves de un Dictionary<TKey,TValue> deben ser únicos según el comparador de igualdad predeterminado.Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer.

La capacidad de un Dictionary<TKey,TValue> es el número de elementos que se pueden agregar a la Dictionary<TKey,TValue> antes de cambiar el tamaño que sea necesario.The capacity of a Dictionary<TKey,TValue> is the number of elements that can be added to the Dictionary<TKey,TValue> before resizing is necessary. Cuando se agregan elementos a un Dictionary<TKey,TValue>, automáticamente se aumenta la capacidad según sea necesario mediante la reasignación de la matriz interna.As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array.

Si se puede estimar el tamaño de la colección, al especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a la Dictionary<TKey,TValue>.If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.This constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation. Como alternativa, puede especificar una implementación de la IEqualityComparer<T> interfaz genérica mediante un constructor que acepta un comparer parámetro.Alternatively, you can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter.

Este constructor es una operación o (1).This constructor is an O(1) operation.

Consulte también:

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que contiene los elementos copiados de la interfaz IDictionary<TKey,TValue> especificada y utiliza la interfaz IEqualityComparer<T> especificada.Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified 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);
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))

Parámetros

comparer
IEqualityComparer<TKey>

Implementación de IEqualityComparer<T> que se va a utilizar para comparar claves o null si se va a utilizar el EqualityComparer<T> predeterminado para el tipo de la clave.The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

Excepciones

El valor de dictionary es null.dictionary is null.

dictionary contiene una o varias claves duplicadas.dictionary contains one or more duplicate keys.

Ejemplos

En el ejemplo de código siguiente se muestra cómo utilizar el Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor para inicializar un Dictionary<TKey,TValue> con mayúsculas y minúsculas contenido ordenado de otro diccionario.The following code example shows how to use the Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor to initialize a Dictionary<TKey,TValue> with case-insensitive sorted content from another dictionary. El ejemplo de código se crea un SortedDictionary<TKey,TValue> con un comparador de mayúsculas y minúsculas y lo rellena con datos en orden aleatorio, a continuación, pasa el SortedDictionary<TKey,TValue> a la Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor, junto con un comparador de igualdad entre mayúsculas y minúsculas, crear un Dictionary<TKey,TValue> que se ordena.The code example creates a SortedDictionary<TKey,TValue> with a case-insensitive comparer and populates it with data in random order, then passes the SortedDictionary<TKey,TValue> to the Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor, along with a case-insensitive equality comparer, creating a Dictionary<TKey,TValue> that is sorted. Esto es útil si necesita crear un diccionario ordenado que en algún momento se convierte en estático; copiar los datos desde un SortedDictionary<TKey,TValue> a un Dictionary<TKey,TValue> mejora la velocidad de recuperación.This is useful if you need to build a sorted dictionary that at some point becomes static; copying the data from a SortedDictionary<TKey,TValue> to a Dictionary<TKey,TValue> improves retrieval speed.

Nota

Cuando se crea un nuevo diccionario con un comparador de mayúsculas y minúsculas y rellenarlo con entradas de un diccionario que se usa a un comparador entre mayúsculas y minúsculas, como en este ejemplo, se produce una excepción si el diccionario de entrada tiene claves que difieran solo por caso.When you create a new dictionary with a case-insensitive comparer and populate it with entries from a dictionary that uses a case-sensitive comparer, as in this example, an exception occurs if the input dictionary has keys that differ only by case.

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

Comentarios

Utilice este constructor con los comparadores de mayúsculas y minúsculas de cadena proporcionados por el StringComparer clase para crear diccionarios con claves de cadena de mayúsculas y minúsculas.Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

Todas las claves de un Dictionary<TKey,TValue> deben ser únicos según la condición especificada comparador; del mismo modo, todas las claves en el origen de dictionary también deben ser únicos según el comparador especificado.Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer; likewise, every key in the source dictionary must also be unique according to the specified comparer.

Nota

Por ejemplo, pueden producirse claves duplicadas si comparer es uno de los comparadores de mayúsculas y minúsculas de cadena proporcionados por el StringComparer clase y dictionary no utiliza una clave de comparador de mayúsculas y minúsculas.For example, duplicate keys can occur if comparer is one of the case-insensitive string comparers provided by the StringComparer class and dictionary does not use a case-insensitive comparer key.

La capacidad inicial del nuevo Dictionary<TKey,TValue> es lo suficientemente grande como para contener todos los elementos de dictionary.The initial capacity of the new Dictionary<TKey,TValue> is large enough to contain all the elements in dictionary.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Si comparer es null, este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

Este constructor es O (n) operación, donde n es el número de elementos de dictionary.This constructor is an O(n) operation, where n is the number of elements in dictionary.

Consulte también:

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

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

Parámetros

collection
IEnumerable<KeyValuePair<TKey,TValue>>
comparer
IEqualityComparer<TKey>

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

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> que está vacía, tiene la capacidad inicial especificada y utiliza el IEqualityComparer<T> especificado.Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>.

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

Parámetros

capacity
Int32 Int32 Int32 Int32

Número inicial de elementos que puede contener la colección Dictionary<TKey,TValue>.The initial number of elements that the Dictionary<TKey,TValue> can contain.

comparer
IEqualityComparer<TKey>

Implementación de IEqualityComparer<T> que se va a utilizar para comparar claves o null si se va a utilizar el EqualityComparer<T> predeterminado para el tipo de la clave.The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

Excepciones

Ejemplos

En el ejemplo de código siguiente se crea un Dictionary<TKey,TValue> con una capacidad inicial de 5 y un comparador de igualdad entre mayúsculas y minúsculas para la referencia cultural actual.The following code example creates a Dictionary<TKey,TValue> with an initial capacity of 5 and a case-insensitive equality comparer for the current culture. El ejemplo agrega cuatro elementos, algunos con claves en minúsculas y otros con claves en mayúsculas.The example adds four elements, some with lower-case keys and some with upper-case keys. El ejemplo se intenta agregar un elemento con una clave que difiere de una clave existente solo por caso, detecta la excepción resultante y muestra un mensaje de error.The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. Por último, el ejemplo muestra los elementos del diccionario.Finally, the example displays the elements in the dictionary.

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

Comentarios

Utilice este constructor con los comparadores de mayúsculas y minúsculas de cadena proporcionados por el StringComparer clase para crear diccionarios con claves de cadena de mayúsculas y minúsculas.Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

Todas las claves de un Dictionary<TKey,TValue> debe ser única según el comparador especificado.Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer.

La capacidad de un Dictionary<TKey,TValue> es el número de elementos que se pueden agregar a la Dictionary<TKey,TValue> antes de cambiar el tamaño que sea necesario.The capacity of a Dictionary<TKey,TValue> is the number of elements that can be added to the Dictionary<TKey,TValue> before resizing is necessary. Cuando se agregan elementos a un Dictionary<TKey,TValue>, automáticamente se aumenta la capacidad según sea necesario mediante la reasignación de la matriz interna.As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array.

Si se puede estimar el tamaño de la colección, al especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a la Dictionary<TKey,TValue>.If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> requiere una implementación de igualdad para determinar si las claves son iguales.Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. Si comparer es null, este constructor utiliza el comparador de igualdad genérico predeterminado, EqualityComparer<T>.Default.If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. Si tipo TKey implementa el System.IEquatable<T> interfaz genérica, el comparador de igualdad predeterminado utiliza esa implementación.If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

Este constructor es una operación o (1).This constructor is an O(1) operation.

Consulte también:

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase Dictionary<TKey,TValue> con datos serializados.Initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

protected:
 Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
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>
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Parámetros

info
SerializationInfo SerializationInfo SerializationInfo SerializationInfo

Objeto SerializationInfo que contiene la información que se requiere para serializar Dictionary<TKey,TValue>.A SerializationInfo object containing the information required to serialize the Dictionary<TKey,TValue>.

context
StreamingContext StreamingContext StreamingContext StreamingContext

Estructura StreamingContext que contiene el origen y el destino de la secuencia serializada asociada a la colección Dictionary<TKey,TValue>.A StreamingContext structure containing the source and destination of the serialized stream associated with the Dictionary<TKey,TValue>.

Comentarios

Este constructor se llama durante la deserialización para reconstituir el objeto transmitido en una secuencia.This constructor is called during deserialization to reconstitute an object transmitted over a stream. Para obtener más información, consulte serialización SOAP y XML.For more information, see XML and SOAP Serialization.

Consulte también:

Se aplica a