Dictionary<TKey,TValue> Construtores
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Inicializa uma nova instância da classe Dictionary<TKey,TValue>.
Sobrecargas
| Nome | Description |
|---|---|
| Dictionary<TKey,TValue>() |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe 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 Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> 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 Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IEnumerable<T>. |
| Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial padrão e usa a especificada IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32) |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe 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 Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e usa o especificado IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IEnumerable<T> e usa o especificado IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial especificada e usa a especificada IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
Obsoleto.
Inicializa uma nova instância da Dictionary<TKey,TValue> classe com dados serializados. |
Dictionary<TKey,TValue>()
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe 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 gera uma 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 =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
let openWith = Dictionary<string, string>()
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// The Add method throws an exception if the new key is
// already in the dictionary.
try
openWith.Add("txt", "winword.exe")
with :? ArgumentException ->
printfn "An element with Key = \"txt\" already exists."
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' The Add method throws an exception if the new key is
' already in the dictionary.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
Comentários
Cada chave em uma 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érico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará 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, o uso de 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>.
Esse construtor é uma operação O(1).
Confira também
Aplica-se a
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> 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>
Os IDictionary<TKey,TValue> elementos 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 e SortedDictionary<TKey,TValue> o preenche com dados em ordem aleatória e, em seguida, passa o SortedDictionary<TKey,TValue> construtor 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
*/
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys.
let openWith = SortedDictionary<string, string>()
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Create a Dictionary of strings with string keys, and
// initialize it with the contents of the sorted dictionary.
let copy = Dictionary<string, string> openWith
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = bmp, Value = paint.exe
// Key = dib, Value = paint.exe
// Key = rtf, Value = wordpad.exe
// Key = txt, Value = notepad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new sorted dictionary of strings, with string
' keys.
Dim openWith As New SortedDictionary(Of String, String)
' Add some elements to the sorted dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Create a Dictionary of strings with string keys, and
' initialize it with the contents of the sorted dictionary.
Dim copy As New Dictionary(Of String, String)(openWith)
' List the contents of the copy.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In copy
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
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érico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará 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>>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IEnumerable<T>.
public:
Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection);
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)))
Parâmetros
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Os IEnumerable<T> elementos 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>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial padrão e usa a especificada IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (comparer As IEqualityComparer(Of TKey))
Parâmetros
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a ser usada ao comparar chaves ou null usar o padrão EqualityComparer<T> para o tipo da chave.
Exemplos
O exemplo de código a seguir cria um Dictionary<TKey,TValue> 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 alguns com chaves maiúsculas. Em seguida, o exemplo tenta adicionar um elemento com uma chave que difere de uma chave existente somente 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
*/
open System
open System.Collections.Generic
// Create a new Dictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
let openWith = Dictionary<string, string> StringComparer.CurrentCultureIgnoreCase
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
openWith.Add("BMP", "paint.exe")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the sorted dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// BMP is already in the dictionary.
//
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new Dictionary of strings, with string keys
' and a case-insensitive comparer for the current culture.
Dim openWith As New Dictionary(Of String, String)( _
StringComparer.CurrentCultureIgnoreCase)
' Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Try to add a fifth element with a key that is the same
' except for case; this would be allowed with the default
' comparer.
Try
openWith.Add("BMP", "paint.exe")
Catch ex As ArgumentException
Console.WriteLine(vbLf & "BMP is already in the dictionary.")
End Try
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
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 uma 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 fornull, esse construtor usará o comparador de igualdade genérico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará essa implementação.
Observação
Se você puder estimar o tamanho da coleção, o uso de 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>.
Esse construtor é uma operação O(1).
Cuidado
Se capacity vier da entrada do usuário, prefira usar um construtor sem um parâmetro de capacidade e permitir que a coleção redimensione à medida que os elementos forem adicionados. Se você precisar usar um valor especificado pelo usuário, fixe-o a um limite razoável (por exemplo) Math.Clamp(untrustedValue, 0, 20)ou verifique se a contagem de elementos corresponde ao valor especificado.
Confira também
Aplica-se a
Dictionary<TKey,TValue>(Int32)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe 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 podem Dictionary<TKey,TValue> 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
*/
open System.Collections.Generic
// Create a new dictionary of strings, with string keys and
// an initial capacity of 4.
let openWith = Dictionary<string, string> 4
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = dib, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys and
' an initial capacity of 4.
Dim openWith As New Dictionary(Of String, String)(4)
' Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
Comentários
Cada chave em uma 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érico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará 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(1).
Cuidado
Se capacity vier da entrada do usuário, prefira usar um construtor sem um parâmetro de capacidade e permitir que a coleção redimensione à medida que os elementos forem adicionados. Se você precisar usar um valor especificado pelo usuário, fixe-o a um limite razoável (por exemplo) Math.Clamp(untrustedValue, 0, 20)ou verifique se a contagem de elementos corresponde ao valor especificado.
Confira também
Aplica-se a
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e usa o especificado IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IEqualityComparer(Of TKey))
Parâmetros
- dictionary
- IDictionary<TKey,TValue>
Os IDictionary<TKey,TValue> elementos cujos elementos são copiados para o novo Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a ser usada ao comparar chaves ou null usar o padrão EqualityComparer<T> para o tipo da 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> conteúdo classificado sem diferenciação de maiúsculas de 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 para SortedDictionary<TKey,TValue> 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
*/
open System
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys and a case-insensitive comparer.
let openWith =
SortedDictionary<string, string> StringComparer.CurrentCultureIgnoreCase
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("Bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Create a Dictionary of strings with string keys and a
// case-insensitive equality comparer, and initialize it
// with the contents of the sorted dictionary.
let copy =
Dictionary<string, string>(openWith, StringComparer.CurrentCultureIgnoreCase)
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = Bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
// Key = txt, Value = notepad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new sorted dictionary of strings, with string
' keys and a case-insensitive comparer.
Dim openWith As New SortedDictionary(Of String, String)( _
StringComparer.CurrentCultureIgnoreCase)
' Add some elements to the sorted dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("Bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Create a Dictionary of strings with string keys and a
' case-insensitive equality comparer, and initialize it
' with the contents of the sorted dictionary.
Dim copy As New Dictionary(Of String, String)(openWith, _
StringComparer.CurrentCultureIgnoreCase)
' List the contents of the copy.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In copy
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
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 uma 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 podem ocorrer se comparer for um dos comparadores de cadeia de caracteres que não diferenciam maiúsculas de minúsculas fornecidos pela StringComparer 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 fornull, esse construtor usará o comparador de igualdade genérico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará essa implementação.
Esse construtor é uma operação O(n), onde n está o número de elementos em dictionary.
Confira também
Aplica-se a
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que contém elementos copiados do especificado IEnumerable<T> e usa o especificado IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)), comparer As IEqualityComparer(Of TKey))
Parâmetros
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Os IEnumerable<T> elementos cujos elementos são copiados para o novo Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a ser usada ao comparar chaves ou null usar o padrão EqualityComparer<T> para o tipo da chave.
Exceções
collection é null.
collection contém uma ou mais chaves duplicadas.
Aplica-se a
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial especificada e usa a especificada IEqualityComparer<T>.
public:
Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer);
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey>? comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of TKey))
Parâmetros
- capacity
- Int32
O número inicial de elementos que podem Dictionary<TKey,TValue> conter.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a ser usada ao comparar chaves ou null usar o padrão EqualityComparer<T> para o tipo da 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 alguns com chaves maiúsculas. Em seguida, o exemplo tenta adicionar um elemento com uma chave que difere de uma chave existente somente 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
*/
open System
open System.Collections.Generic
// Create a new dictionary of strings, with string keys, an
// initial capacity of 5, and a case-insensitive equality
// comparer.
let openWith =
Dictionary<string, string>(5, StringComparer.CurrentCultureIgnoreCase)
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
openWith.Add("BMP", "paint.exe")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// BMP is already in the dictionary.
//
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new Dictionary of strings, with string keys, an
' initial capacity of 5, and a case-insensitive equality
' comparer.
Dim openWith As New Dictionary(Of String, String)(5, _
StringComparer.CurrentCultureIgnoreCase)
' Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Try to add a fifth element with a key that is the same
' except for case; this would be allowed with the default
' comparer.
Try
openWith.Add("BMP", "paint.exe")
Catch ex As ArgumentException
Console.WriteLine(vbLf & "BMP is already in the dictionary.")
End Try
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
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 uma 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 fornull, esse construtor usará o comparador de igualdade genérico padrão. EqualityComparer<T>.Default Se o tipo TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade padrão usará essa implementação.
Esse construtor é uma operação O(1).
Confira também
Aplica-se a
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- Dictionary.cs
- Origem:
- 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 Dictionary<TKey,TValue> classe com dados serializados.
protected:
Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
Protected Sub New (info As SerializationInfo, context As StreamingContext)
Parâmetros
- info
- SerializationInfo
Um SerializationInfo objeto que contém as informações necessárias para serializar o Dictionary<TKey,TValue>.
- context
- StreamingContext
Uma StreamingContext estrutura 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 de serialização XML e SOAP.