Dictionary<TKey,TValue> Construtores

Definição

Inicializa uma nova instância da classe Dictionary<TKey,TValue>.

Sobrecargas

Dictionary<TKey,TValue>()

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial padrão e usa o comparador de igualdade padrão para o tipo de chave.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém os elementos copiados do IDictionary<TKey,TValue> especificado e usa o comparador de igualdade padrão para o tipo de chave.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados do IEnumerable<T> especificado.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial padrão e usa o IEqualityComparer<T> especificado.

Dictionary<TKey,TValue>(Int32)

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial especificada e usa o comparador de igualdade padrão para o tipo de chave.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados da IDictionary<TKey,TValue> especificada e usa o IEqualityComparer<T> especificado.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados da IEnumerable<T> especificada e usa o IEqualityComparer<T> especificado.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial especificada e usa o IEqualityComparer<T> especificado.

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> com dados serializados.

Dictionary<TKey,TValue>()

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial padrão e usa o comparador de igualdade padrão para o tipo de chave.

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

Exemplos

O exemplo de código a seguir cria um vazio Dictionary<TKey,TValue> de cadeias de caracteres com chaves de cadeia de caracteres e usa o Add método para adicionar alguns elementos. O exemplo demonstra que o Add método lança um ArgumentException ao tentar adicionar uma chave duplicada.

Este exemplo de código faz parte de um exemplo maior fornecido para a Dictionary<TKey,TValue> classe .

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

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
    Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)

' Add some elements to the dictionary. There are no 
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is 
' already in the dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

Comentários

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador de igualdade padrão.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Esse construtor usa o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação. Como alternativa, você pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceita um comparer parâmetro.

Observação

Se você puder estimar o tamanho da coleção, usar um construtor que especifica a capacidade inicial eliminará a necessidade de executar várias operações de redimensionamento ao adicionar elementos ao Dictionary<TKey,TValue>.

Este construtor é uma operação O(1).

Confira também

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém os elementos copiados do IDictionary<TKey,TValue> especificado e usa o comparador de igualdade padrão para o tipo de chave.

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

dictionary
IDictionary<TKey,TValue>

O IDictionary<TKey,TValue> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.

Exceções

dictionary é null.

dictionary contém uma ou mais chaves duplicadas.

Exemplos

O exemplo de código a seguir mostra como usar o Dictionary<TKey,TValue>(IEqualityComparer<TKey>) construtor para inicializar um Dictionary<TKey,TValue> com conteúdo classificado de outro dicionário. O exemplo de código cria um SortedDictionary<TKey,TValue> e o preenche com dados em ordem aleatória e, em seguida, passa o SortedDictionary<TKey,TValue> para o Dictionary<TKey,TValue>(IEqualityComparer<TKey>) construtor, criando um Dictionary<TKey,TValue> classificado. Isso será útil se você precisar criar um dicionário classificado que, em algum momento, se torne estático; copiar os dados de um SortedDictionary<TKey,TValue> para um Dictionary<TKey,TValue> melhora a velocidade de recuperação.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Comentários

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador de igualdade padrão; da mesma forma, cada chave na origem dictionary também deve ser exclusiva de acordo com o comparador de igualdade padrão.

A capacidade inicial do novo Dictionary<TKey,TValue> é grande o suficiente para conter todos os elementos em dictionary.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Esse construtor usa o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação. Como alternativa, você pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceita um comparer parâmetro.

Esse construtor é uma operação O(n), em que n é o número de elementos em dictionary.

Confira também

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados do IEnumerable<T> especificado.

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

O IEnumerable<T> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.

Exceções

collection é null.

collection contém uma ou mais chaves duplicadas.

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial padrão e usa o IEqualityComparer<T> especificado.

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

Parâmetros

comparer
IEqualityComparer<TKey>

A implementação IEqualityComparer<T> a ser usada na comparação de chaves ou null para usar o EqualityComparer<T> padrão para o tipo de chave.

Exemplos

O exemplo de código a seguir cria um Dictionary<TKey,TValue> com um comparador de igualdade que não diferencia maiúsculas de minúsculas para a cultura atual. O exemplo adiciona quatro elementos, alguns com chaves minúsculas e outros com chaves maiúsculas. Em seguida, o exemplo tenta adicionar um elemento com uma chave que difere de uma chave existente apenas por caso, captura a exceção resultante e exibe uma mensagem de erro. Por fim, o exemplo exibe os elementos no dicionário.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

BMP is already in the dictionary.

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Comentários

Use esse construtor com os comparadores de cadeia de caracteres que não diferenciam maiúsculas de minúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de cadeia de caracteres que não diferenciam maiúsculas de minúsculas.

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador especificado.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Se comparer for null, esse construtor usará o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação.

Observação

Se você puder estimar o tamanho da coleção, usar um construtor que especifica a capacidade inicial eliminará a necessidade de executar várias operações de redimensionamento ao adicionar elementos ao Dictionary<TKey,TValue>.

Este construtor é uma operação O(1).

Confira também

Aplica-se a

Dictionary<TKey,TValue>(Int32)

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial especificada e usa o comparador de igualdade padrão para o tipo de chave.

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

O número inicial de elementos que o Dictionary<TKey,TValue> pode conter.

Exceções

capacity é menor que 0.

Exemplos

O exemplo de código a seguir cria um dicionário com uma capacidade inicial de 4 e o preenche com 4 entradas.

using System;
using System.Collections.Generic;

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

    End Sub

End Class

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

Comentários

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador de igualdade padrão.

A capacidade de um Dictionary<TKey,TValue> é o número de elementos que podem ser adicionados ao antes que o Dictionary<TKey,TValue> redimensionamento seja necessário. À medida que os elementos são adicionados a um Dictionary<TKey,TValue>, a capacidade é automaticamente aumentada conforme exigido pela realocação da matriz interna.

Se o tamanho da coleção puder ser estimado, especificar a capacidade inicial eliminará a necessidade de executar várias operações de redimensionamento ao adicionar elementos ao Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Esse construtor usa o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação. Como alternativa, você pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceita um comparer parâmetro.

Este construtor é uma operação O(1).

Confira também

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados da IDictionary<TKey,TValue> especificada e usa o IEqualityComparer<T> especificado.

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

Parâmetros

dictionary
IDictionary<TKey,TValue>

O IDictionary<TKey,TValue> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

A implementação IEqualityComparer<T> a ser usada na comparação de chaves ou null para usar o EqualityComparer<T> padrão para o tipo de chave.

Exceções

dictionary é null.

dictionary contém uma ou mais chaves duplicadas.

Exemplos

O exemplo de código a seguir mostra como usar o Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) construtor para inicializar um Dictionary<TKey,TValue> com conteúdo classificado sem diferenciação de maiúsculas e minúsculas de outro dicionário. O exemplo de código cria um SortedDictionary<TKey,TValue> com um comparador que não diferencia maiúsculas de minúsculas e o preenche com dados em ordem aleatória e, em seguida, passa o SortedDictionary<TKey,TValue> para o Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) construtor, juntamente com um comparador de igualdade que não diferencia maiúsculas de minúsculas, criando um Dictionary<TKey,TValue> classificado. Isso será útil se você precisar criar um dicionário classificado que, em algum momento, se torne estático; copiar os dados de um SortedDictionary<TKey,TValue> para um Dictionary<TKey,TValue> melhora a velocidade de recuperação.

Observação

Quando você cria um novo dicionário com um comparador que não diferencia maiúsculas de minúsculas e o preenche com entradas de um dicionário que usa um comparador que diferencia maiúsculas de minúsculas, como neste exemplo, ocorre uma exceção se o dicionário de entrada tiver chaves que diferem apenas por caso.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Comentários

Use esse construtor com os comparadores de cadeia de caracteres que não diferenciam maiúsculas de minúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de cadeia de caracteres que não diferenciam maiúsculas de minúsculas.

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador especificado; da mesma forma, cada chave na origem dictionary também deve ser exclusiva de acordo com o comparador especificado.

Observação

Por exemplo, chaves duplicadas poderão ocorrer se comparer for um dos comparadores de cadeia de caracteres que não diferenciam maiúsculas StringComparer de minúsculas fornecidos pela classe e dictionary não usar uma chave comparador que não diferencia maiúsculas de minúsculas.

A capacidade inicial do novo Dictionary<TKey,TValue> é grande o suficiente para conter todos os elementos em dictionary.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Se comparer for null, esse construtor usará o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação.

Esse construtor é uma operação O(n), em que n é o número de elementos em dictionary.

Confira também

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que contém elementos copiados da IEnumerable<T> especificada e usa o IEqualityComparer<T> especificado.

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

Parâmetros

collection
IEnumerable<KeyValuePair<TKey,TValue>>

O IEnumerable<T> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

A implementação IEqualityComparer<T> a ser usada na comparação de chaves ou null para usar o EqualityComparer<T> padrão para o tipo de chave.

Exceções

collection é null.

collection contém uma ou mais chaves duplicadas.

Aplica-se a

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

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> que está vazia, tem a capacidade inicial especificada e usa o IEqualityComparer<T> especificado.

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

Parâmetros

capacity
Int32

O número inicial de elementos que o Dictionary<TKey,TValue> pode conter.

comparer
IEqualityComparer<TKey>

A implementação IEqualityComparer<T> a ser usada na comparação de chaves ou null para usar o EqualityComparer<T> padrão para o tipo de chave.

Exceções

capacity é menor que 0.

Exemplos

O exemplo de código a seguir cria um Dictionary<TKey,TValue> com uma capacidade inicial de 5 e um comparador de igualdade que não diferencia maiúsculas de minúsculas para a cultura atual. O exemplo adiciona quatro elementos, alguns com chaves minúsculas e outros com chaves maiúsculas. Em seguida, o exemplo tenta adicionar um elemento com uma chave que difere de uma chave existente apenas por caso, captura a exceção resultante e exibe uma mensagem de erro. Por fim, o exemplo exibe os elementos no dicionário.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

BMP is already in the dictionary.

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Comentários

Use esse construtor com os comparadores de cadeia de caracteres que não diferenciam maiúsculas de minúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de cadeia de caracteres que não diferenciam maiúsculas de minúsculas.

Cada chave em um Dictionary<TKey,TValue> deve ser exclusiva de acordo com o comparador especificado.

A capacidade de um Dictionary<TKey,TValue> é o número de elementos que podem ser adicionados ao antes que o Dictionary<TKey,TValue> redimensionamento seja necessário. À medida que os elementos são adicionados a um Dictionary<TKey,TValue>, a capacidade é automaticamente aumentada conforme exigido pela realocação da matriz interna.

Se o tamanho da coleção puder ser estimado, especificar a capacidade inicial eliminará a necessidade de executar várias operações de redimensionamento ao adicionar elementos ao Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Se comparer for null, esse construtor usará o comparador de igualdade genérica padrão, EqualityComparer<T>.Default. Caso o tipo TKey implemente a interface genérica System.IEquatable<T>, a comparação de igualdade padrão usa essa implementação.

Este construtor é uma operação O(1).

Confira também

Aplica-se a

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

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

Cuidado

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

Inicializa uma nova instância da classe Dictionary<TKey,TValue> com dados serializados.

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

Parâmetros

info
SerializationInfo

Um objeto SerializationInfo que contém as informações necessárias para serializar o Dictionary<TKey,TValue>.

context
StreamingContext

Uma estrutura StreamingContext que contém a origem e o destino do fluxo serializado associado ao Dictionary<TKey,TValue>.

Atributos

Comentários

Esse construtor é chamado durante a desserialização para reconstituir um objeto transmitido por um fluxo. Para obter mais informações, consulte serialização XML e SOAP.

Confira também

Aplica-se a