Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Class

Definition

Representa una colección de claves y valores. Represents a collection of keys and values.

generic <typename TKey, typename TValue>
public ref class Dictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IDictionary<TKey, TValue>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyCollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyDictionary<TKey, TValue>, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[Serializable]
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Dictionary<'Key, 'Value> = class
    interface IDictionary<'Key, 'Value>
    interface IDictionary
    interface IReadOnlyDictionary<'Key, 'Value>
    interface ISerializable
    interface IDeserializationCallback
    interface ICollection<KeyValuePair<'Key, 'Value>>
    interface seq<KeyValuePair<'Key, 'Value>>
    interface IEnumerable
    interface ICollection
    interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
Public Class Dictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDeserializationCallback, IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), IReadOnlyCollection(Of KeyValuePair(Of TKey, TValue)), IReadOnlyDictionary(Of TKey, TValue), ISerializable

Type Parameters

TKey

Tipo de las claves del diccionario. The type of the keys in the dictionary.

TValue

Tipo de los valores del diccionario. The type of the values in the dictionary.

Inheritance
Dictionary<TKey,TValue>Dictionary<TKey,TValue>Dictionary<TKey,TValue>Dictionary<TKey,TValue>
Derived
Attributes
ComVisibleAttribute SerializableAttribute
Implements

Examples

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.

El ejemplo se usa el Item[TKey] propiedad (el indizador en C#) para recuperar valores, lo que demuestra que un KeyNotFoundException se produce cuando una clave solicitada no está presente, y que el valor asociado a una clave se puede reemplazar.The example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

En el ejemplo se muestra cómo utilizar el TryGetValue método como una forma más eficaz para recuperar valores si un programa debe probar con frecuencia valores de clave que no están en el diccionario, y muestra cómo utilizar el ContainsKey método para comprobar si existe una clave antes de llamar a la Add método.The example shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary, and it shows how to use the ContainsKey method to test whether a key exists before calling the Add method.

En el ejemplo se muestra cómo enumerar las claves y valores del diccionario y cómo enumerar las claves y los valores por sí solo mediante la Keys propiedad y el Values propiedad.The example shows how to enumerate the keys and values in the dictionary and how to enumerate the keys and values alone using the Keys property and the Values property.

Por último, en el ejemplo se muestra el Remove método.Finally, the example demonstrates the Remove method.

using namespace System;
using namespace System::Collections::Generic;

public ref class Example
{
public:
    static void Main()
    {
        // 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.");
        }

        // The Item property is another name for the indexer, so you
        // can omit its name when accessing elements.
        Console::WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console::WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console::WriteLine("For key = \"tif\", value = {0}.",
                openWith["tif"]);
        }
        catch (KeyNotFoundException^)
        {
            Console::WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient
        // way to retrieve values.
        String^ value = "";
        if (openWith->TryGetValue("tif", value))
        {
            Console::WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console::WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting
        // them.
        if (!openWith->ContainsKey("ht"))
        {
            openWith->Add("ht", "hypertrm.exe");
            Console::WriteLine("Value added for key = \"ht\": {0}",
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console::WriteLine();
        for each( KeyValuePair<String^, String^> kvp in openWith )
        {
            Console::WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        Dictionary<String^, String^>::ValueCollection^ valueColl =
            openWith->Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console::WriteLine();
        for each( String^ s in valueColl )
        {
            Console::WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<String^, String^>::KeyCollection^ keyColl =
            openWith->Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console::WriteLine();
        for each( String^ s in keyColl )
        {
            Console::WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console::WriteLine("\nRemove(\"doc\")");
        openWith->Remove("doc");

        if (!openWith->ContainsKey("doc"))
        {
            Console::WriteLine("Key \"doc\" is not found.");
        }
    }
};

int main()
{
    Example::Main();
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // 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.");
        }

        // The Item property is another name for the indexer, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", 
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", 
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        Dictionary<string, string>.ValueCollection valueColl =
            openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */
Imports System
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' 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

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' The default Item property throws an exception if the requested
        ' key is not in the dictionary.
        Try
            Console.WriteLine("For key = ""tif"", value = {0}.", _
                openWith("tif"))
        Catch 
            Console.WriteLine("Key = ""tif"" is not found.")
        End Try

        ' When a program often has to try keys that turn out not to
        ' be in the dictionary, TryGetValue can be a more efficient 
        ' way to retrieve values.
        Dim value As String = ""
        If openWith.TryGetValue("tif", value) Then
            Console.WriteLine("For key = ""tif"", value = {0}.", value)
        Else
            Console.WriteLine("Key = ""tif"" is not found.")
        End If

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
                openWith("ht"))
        End If

        ' When you use foreach to enumerate dictionary elements,
        ' the elements are retrieved as KeyValuePair objects.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

        ' To get the values alone, use the Values property.
        Dim valueColl As _
            Dictionary(Of String, String).ValueCollection = _
            openWith.Values
        
        ' The elements of the ValueCollection are strongly typed
        ' with the type that was specified for dictionary values.
        Console.WriteLine()
        For Each s As String In  valueColl
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl As _
            Dictionary(Of String, String).KeyCollection = _
            openWith.Keys
        
        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for dictionary keys.
        Console.WriteLine()
        For Each s As String In  keyColl
            Console.WriteLine("Key = {0}", s)
        Next s

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        openWith.Remove("doc")
        
        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Class

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Key = "tif" is not found.
'Key = "tif" is not found.
'Value added for key = "ht": hypertrm.exe
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'
'Value = notepad.exe
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'Value = hypertrm.exe
'
'Key = txt
'Key = bmp
'Key = dib
'Key = rtf
'Key = doc
'Key = ht
'
'Remove("doc")
'Key "doc" is not found.
' 

Remarks

La Dictionary<TKey,TValue> clase genérica proporciona una asignación de un conjunto de claves a un conjunto de valores.The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. Cada adición al diccionario consta de un valor y de su clave asociada.Each addition to the dictionary consists of a value and its associated key. Recuperar un valor con su clave es muy rápido, cerrar o (1), porque la Dictionary<TKey,TValue> clase se implementa como una tabla hash.Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table.

Nota

La velocidad de recuperación depende de la calidad del algoritmo hash del tipo especificado para TKey.The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

Siempre que un objeto se usa como clave en el Dictionary<TKey,TValue>, no debe cambiar de manera que afecta a su valor hash.As long as an object is used as a key in the Dictionary<TKey,TValue>, it must not change in any way that affects its hash value. Todas las claves de un Dictionary<TKey,TValue> deben ser únicos según el comparador de igualdad del diccionario.Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer. No puede ser una clave null, pero un valor valor puede ser, si el valor de tipo TValue es un tipo de referencia.A key cannot be null, but a value can be, if the value type TValue is a reference type.

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. Puede especificar una implementación de la IEqualityComparer<T> interfaz genérica mediante un constructor que acepta un comparer parámetro; si no especifica una implementación, el comparador de igualdad genérico predeterminado EqualityComparer<T>.Default se utiliza.You can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer<T>.Default is used. 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

Por ejemplo, puede utilizar 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.For example, you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

La capacidad de un Dictionary<TKey,TValue> es el número de elementos de la Dictionary<TKey,TValue> puede contener.The capacity of a Dictionary<TKey,TValue> is the number of elements the Dictionary<TKey,TValue> can hold. 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.

Para grandes Dictionary<TKey,TValue> objetos, puede aumentar la capacidad máxima de 2 millones de elementos en un sistema de 64 bits estableciendo el enabled atributo del elemento de configuración para true en el entorno de tiempo de ejecución.For very large Dictionary<TKey,TValue> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

Para fines de enumeración, cada elemento en el diccionario se trata como un KeyValuePair<TKey,TValue> estructura que representa un valor y su clave.For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. El orden en que se devuelven los elementos es indefinido.The order in which the items are returned is undefined.

El foreach instrucción del lenguaje C# (for each en C++, For Each en Visual Basic) devuelve un objeto del tipo de los elementos de la colección.The foreach statement of the C# language (for each in C++, For Each in Visual Basic) returns an object of the type of the elements in the collection. Puesto que la Dictionary<TKey,TValue> es una colección de claves y valores, el tipo de elemento no es el tipo de la clave o el tipo del valor.Since the Dictionary<TKey,TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. En su lugar, el tipo de elemento es un KeyValuePair<TKey,TValue> del tipo de clave y el tipo de valor.Instead, the element type is a KeyValuePair<TKey,TValue> of the key type and the value type. Por ejemplo:For example:

for each(KeyValuePair<String^, String^> kvp in myDictionary)
{
    Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of String, String) In myDictionary
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp

El foreach instrucción es un contenedor del enumerador, que sólo permite la lectura de la colección, no escribir en él.The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

Nota

Dado que las claves se pueden heredar y su comportamiento puede cambiar, no se puede garantizar su unicidad absoluta mediante comparaciones utilizando el Equals método.Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

Constructors

Dictionary<TKey,TValue>() 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>(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>>) 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>>, 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>(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>(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.

Properties

Comparer Comparer Comparer Comparer

Obtiene la interfaz IEqualityComparer<T> que se utiliza para determinar la igualdad de claves para el diccionario. Gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.

Count Count Count Count

Obtiene el número de pares clave-valor incluidos en Dictionary<TKey,TValue>. Gets the number of key/value pairs contained in the Dictionary<TKey,TValue>.

Item[TKey] Item[TKey] Item[TKey] Item[TKey]

Obtiene o establece el valor asociado a la clave especificada. Gets or sets the value associated with the specified key.

Keys Keys Keys Keys

Obtiene una colección que contiene las claves de Dictionary<TKey,TValue>. Gets a collection containing the keys in the Dictionary<TKey,TValue>.

Values Values Values Values

Obtiene una colección que contiene los valores de Dictionary<TKey,TValue>. Gets a collection containing the values in the Dictionary<TKey,TValue>.

Methods

Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue)

Agrega la clave y el valor especificados al diccionario. Adds the specified key and value to the dictionary.

Clear() Clear() Clear() Clear()

Quita todas las claves y valores de Dictionary<TKey,TValue>. Removes all keys and values from the Dictionary<TKey,TValue>.

ContainsKey(TKey) ContainsKey(TKey) ContainsKey(TKey) ContainsKey(TKey)

Determina si Dictionary<TKey,TValue> contiene la clave especificada. Determines whether the Dictionary<TKey,TValue> contains the specified key.

ContainsValue(TValue) ContainsValue(TValue) ContainsValue(TValue) ContainsValue(TValue)

Determina si Dictionary<TKey,TValue> contiene un valor específico. Determines whether the Dictionary<TKey,TValue> contains a specific value.

EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual. Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Devuelve un enumerador que recorre en iteración la colección Dictionary<TKey,TValue>. Returns an enumerator that iterates through the Dictionary<TKey,TValue>.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada. Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Implementa la interfaz de ISerializable y devuelve los datos necesarios para serializar la instancia de Dictionary<TKey,TValue>. Implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual. Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual. Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object)

Implementa la interfaz ISerializable y genera el evento de deserialización cuando esta ha finalizado. Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(TKey) Remove(TKey) Remove(TKey) Remove(TKey)

Quita el valor con la clave especificada de la colección Dictionary<TKey,TValue>. Removes the value with the specified key from the Dictionary<TKey,TValue>.

Remove(TKey, TValue) Remove(TKey, TValue) Remove(TKey, TValue) Remove(TKey, TValue)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual. Returns a string that represents the current object.

(Inherited from Object)
TrimExcess() TrimExcess() TrimExcess() TrimExcess()
TrimExcess(Int32) TrimExcess(Int32) TrimExcess(Int32) TrimExcess(Int32)
TryAdd(TKey, TValue) TryAdd(TKey, TValue) TryAdd(TKey, TValue) TryAdd(TKey, TValue)
TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue)

Obtiene el valor asociado a la clave especificada. Gets the value associated with the specified key.

Explicit Interface Implementations

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

Copia los elementos ICollection<T> en una matriz, comenzando en el índice especificado de la matriz. Copies the elements of the ICollection<T> to an array, starting at the specified array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

Obtiene un valor que indica si el acceso a la interfaz ICollection está sincronizado (es seguro para subprocesos). Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Obtiene un objeto que se puede usar para sincronizar el acceso a ICollection. Gets an object that can be used to synchronize access to the ICollection.

ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>)
ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>)
ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32)
ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly
ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>)
IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object)

Agrega la clave y el valor especificados al diccionario. Adds the specified key and value to the dictionary.

IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object)

Determina si IDictionary contiene un elemento con la clave especificada. Determines whether the IDictionary contains an element with the specified key.

IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator()

Devuelve una interfaz IDictionaryEnumerator para la interfaz IDictionary. Returns an IDictionaryEnumerator for the IDictionary.

IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize

Obtiene un valor que indica si la interfaz IDictionary tiene un tamaño fijo. Gets a value indicating whether the IDictionary has a fixed size.

IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly

Obtiene un valor que indica si IDictionary es de solo lectura. Gets a value indicating whether the IDictionary is read-only.

IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object]

Obtiene o establece el valor con la clave especificada. Gets or sets the value with the specified key.

IDictionary.Keys IDictionary.Keys IDictionary.Keys IDictionary.Keys

Obtiene una interfaz ICollection que contiene las claves de la interfaz IDictionary. Gets an ICollection containing the keys of the IDictionary.

IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object)

Quita el elemento con la clave especificada de IDictionary. Removes the element with the specified key from the IDictionary.

IDictionary.Values IDictionary.Values IDictionary.Values IDictionary.Values

Obtiene una interfaz ICollection que contiene los valores de la interfaz IDictionary. Gets an ICollection containing the values in the IDictionary.

IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys
IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values
IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Devuelve un enumerador que procesa una iteración en la colección. Returns an enumerator that iterates through the collection.

IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator()
IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys
IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values

Applies to

Thread Safety

Un Dictionary<TKey,TValue> puede admitir varios lectores simultáneamente, siempre y cuando no se modifica la colección. A Dictionary<TKey,TValue> can support multiple readers concurrently, as long as the collection is not modified. Aun así, enumerar una colección no es un procedimiento seguro para subprocesos. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. En el caso excepcional donde una enumeración debe enfrentarse a los accesos de escritura, la colección debe estar bloqueada durante toda la enumeración. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. Para permitir que varios subprocesos obtengan acceso de lectura y escritura a la colección, debe implementar su propia sincronización. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. Para alternativas de subprocesos, consulte la ConcurrentDictionary<TKey,TValue> clase o ImmutableDictionary<TKey,TValue> clase. For thread-safe alternatives, see the ConcurrentDictionary<TKey,TValue> class or ImmutableDictionary<TKey,TValue> class. Estáticos públicos (Shared en Visual Basic) los miembros de este tipo son seguros para subprocesos. Public static (Shared in Visual Basic) members of this type are thread safe.

See Also