Dictionary<TKey,TValue> Construtores
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Inicializa uma nova instância da Dictionary<TKey,TValue> classe.
Sobrecargas
| Name | 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 utiliza 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 o especificado 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 o .IEqualityComparer<T> |
| Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da Dictionary<TKey,TValue> classe com dados serializados. |
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.
public:
Dictionary();
public Dictionary();
Public Sub New ()
Exemplos
O exemplo de código seguinte cria um vazio Dictionary<TKey,TValue> de strings com chaves string 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 =
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
Observações
Cada chave em um Dictionary<TKey,TValue> deve ser única segundo o comparador de igualdade padrão.
Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Este construtor utiliza o comparador de igualdade genérico por defeito, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação. Em alternativa, pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceite um comparer parâmetro.
Note
Se conseguir estimar o tamanho da coleção, usar um construtor que especifique a capacidade inicial elimina a necessidade de realizar várias operações de redimensionamento enquanto se adicionam elementos ao Dictionary<TKey,TValue>.
Este construtor é uma operação O(1).
Ver também
Aplica-se a
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 utiliza 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> 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 seguinte mostra como usar o Dictionary<TKey,TValue>(IEqualityComparer<TKey>) construtor para inicializar um Dictionary<TKey,TValue> com conteúdo ordenado a partir de outro dicionário. O exemplo de código cria a SortedDictionary<TKey,TValue> e preenche-o com dados por ordem aleatória, depois passa o SortedDictionary<TKey,TValue> para o Dictionary<TKey,TValue>(IEqualityComparer<TKey>) construtor, criando um Dictionary<TKey,TValue> que é ordenado. Isto é útil se precisares de construir um dicionário ordenado que, em algum momento, se torna estático; Copiar os dados de A SortedDictionary<TKey,TValue> para A 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
Observações
Cada chave em a Dictionary<TKey,TValue> deve ser única segundo o comparador de igualdade padrão; da mesma forma, cada chave na fonte dictionary também deve ser única segundo o comparador de igualdade padrão.
A capacidade inicial do novo Dictionary<TKey,TValue> é suficientemente grande para conter todos os elementos em dictionary.
Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Este construtor utiliza o comparador de igualdade genérico por defeito, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação. Em alternativa, pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceite um comparer parâmetro.
Este construtor é uma operação O(n), onde n é o número de elementos em dictionary.
Ver também
Aplica-se a
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>.
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> 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>)
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial padrão e usa o especificado IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (comparer As IEqualityComparer(Of TKey))
Parâmetros
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a usar ao comparar chaves, ou null usar o padrão EqualityComparer<T> para o tipo da chave.
Exemplos
O seguinte exemplo de código cria um Dictionary<TKey,TValue> com um comparador de igualdade insensível a maiúsculas minúsculas para a cultura atual. O exemplo acrescenta quatro elementos, alguns com letras minúsculas e outros com maiúsculas. O exemplo tenta então adicionar um elemento com uma chave que difere de uma chave existente apenas por caso, apanha a exceção resultante e apresenta uma mensagem de erro. Finalmente, o exemplo mostra 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
Observações
Use este construtor com os comparadores de strings insensíveis a maiúsculas e maiúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de strings insensíveis a maiúsculas minúsculas.
Cada chave em um Dictionary<TKey,TValue> deve ser única 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, este construtor usa o comparador genérico de igualdade padrão, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação.
Note
Se conseguir estimar o tamanho da coleção, usar um construtor que especifique a capacidade inicial elimina a necessidade de realizar várias operações de redimensionamento enquanto se adicionam elementos ao Dictionary<TKey,TValue>.
Este construtor é uma operação O(1).
Atenção
Se capacity provém da entrada do utilizador, prefira usar um construtor sem parâmetro de capacidade e deixar a coleção redimensionar-se à medida que os elementos são adicionados. Se tiver de usar um valor especificado pelo utilizador, ou limite-o a um limite razoável (por exemplo, Math.Clamp(untrustedValue, 0, 20)) ou verifique se a contagem de elementos corresponde ao valor especificado.
Ver também
Aplica-se a
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.
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 é inferior a 0.
Exemplos
O exemplo de código seguinte cria um dicionário com uma capacidade inicial de 4 e preenche-o 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
Observações
Cada chave em um Dictionary<TKey,TValue> deve ser única segundo o comparador de igualdade padrão.
A capacidade de a Dictionary<TKey,TValue> é o número de elementos que podem ser adicionados a antes Dictionary<TKey,TValue> de ser necessário redimensionar. À medida que elementos são adicionados a um Dictionary<TKey,TValue>, a capacidade é automaticamente aumentada conforme necessário ao realocar o array interno.
Se o tamanho da coleção puder ser estimado, especificar a capacidade inicial elimina a necessidade de realizar várias operações de redimensionamento enquanto se adicionam elementos ao Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> requer uma implementação de igualdade para determinar se as chaves são iguais. Este construtor utiliza o comparador de igualdade genérico por defeito, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação. Em alternativa, pode especificar uma implementação da IEqualityComparer<T> interface genérica usando um construtor que aceite um comparer parâmetro.
Este construtor é uma operação O(1).
Atenção
Se capacity provém da entrada do utilizador, prefira usar um construtor sem parâmetro de capacidade e deixar a coleção redimensionar-se à medida que os elementos são adicionados. Se tiver de usar um valor especificado pelo utilizador, ou limite-o a um limite razoável (por exemplo, Math.Clamp(untrustedValue, 0, 20)) ou verifique se a contagem de elementos corresponde ao valor especificado.
Ver também
Aplica-se a
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>.
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> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a usar 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 seguinte mostra como usar o Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) construtor para inicializar um Dictionary<TKey,TValue> com conteúdo ordenado insensível a maiúsculas minúsculas a partir de outro dicionário. O exemplo de código cria a SortedDictionary<TKey,TValue> com um comparador insensível a maiúsculas e minúsculas e preenche-o com dados por ordem aleatória, depois passa o SortedDictionary<TKey,TValue> para o Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) construtor, juntamente com um comparador de igualdade insensível a maiúsculas e minúsculas, criando um Dictionary<TKey,TValue> que é ordenado. Isto é útil se precisares de construir um dicionário ordenado que, em algum momento, se torna estático; Copiar os dados de A SortedDictionary<TKey,TValue> para A Dictionary<TKey,TValue> melhora a velocidade de recuperação.
Note
Quando cria um novo dicionário com um comparador insensível a maiúsculas minúsculas e o preenche com entradas de um dicionário que usa um comparador sensível a maiúsculas 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
Observações
Use este construtor com os comparadores de strings insensíveis a maiúsculas e maiúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de strings insensíveis a maiúsculas minúsculas.
Cada chave em a Dictionary<TKey,TValue> deve ser única de acordo com o comparador especificado; da mesma forma, cada chave na fonte dictionary também deve ser única de acordo com o comparador especificado.
Note
Por exemplo, chaves duplicadas podem ocorrer se comparer for um dos comparadores de strings insensíveis a maiúsculas minúsculas fornecidos pela StringComparer classe e dictionary não usar uma chave de comparação insensível a maiúsculas.
A capacidade inicial do novo Dictionary<TKey,TValue> é suficientemente grande 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, este construtor usa o comparador genérico de igualdade padrão, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação.
Este construtor é uma operação O(n), onde n é o número de elementos em dictionary.
Ver também
Aplica-se a
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>.
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> cujos elementos são copiados para o novo Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a usar 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>)
Inicializa uma nova instância da Dictionary<TKey,TValue> classe que está vazia, tem a capacidade inicial especificada e usa o .IEqualityComparer<T>
public:
Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of TKey))
Parâmetros
- capacity
- Int32
O número inicial de elementos que podem Dictionary<TKey,TValue> conter.
- comparer
- IEqualityComparer<TKey>
A IEqualityComparer<T> implementação a usar ao comparar chaves, ou null usar o padrão EqualityComparer<T> para o tipo da chave.
Exceções
capacity é inferior a 0.
Exemplos
O exemplo de código seguinte cria um Dictionary<TKey,TValue> com uma capacidade inicial de 5 e um comparador de igualdade insensível a maiúsculas minúsculas para a cultura atual. O exemplo acrescenta quatro elementos, alguns com letras minúsculas e outros com maiúsculas. O exemplo tenta então adicionar um elemento com uma chave que difere de uma chave existente apenas por caso, apanha a exceção resultante e apresenta uma mensagem de erro. Finalmente, o exemplo mostra 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
Observações
Use este construtor com os comparadores de strings insensíveis a maiúsculas e maiúsculas fornecidos pela StringComparer classe para criar dicionários com chaves de strings insensíveis a maiúsculas minúsculas.
Cada chave em um Dictionary<TKey,TValue> deve ser única de acordo com o comparador especificado.
A capacidade de a Dictionary<TKey,TValue> é o número de elementos que podem ser adicionados a antes Dictionary<TKey,TValue> de ser necessário redimensionar. À medida que elementos são adicionados a um Dictionary<TKey,TValue>, a capacidade é automaticamente aumentada conforme necessário ao realocar o array interno.
Se o tamanho da coleção puder ser estimado, especificar a capacidade inicial elimina a necessidade de realizar várias operações de redimensionamento enquanto se adicionam 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, este construtor usa o comparador genérico de igualdade padrão, EqualityComparer<T>.Default. Se o type TKey implementar a System.IEquatable<T> interface genérica, o comparador de igualdade por defeito usa essa implementação.
Este construtor é uma operação O(1).
Ver também
Aplica-se a
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
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);
protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
Protected Sub New (info As SerializationInfo, context As StreamingContext)
Parâmetros
- info
- SerializationInfo
Um SerializationInfo objeto contendo a informação necessária para serializar o Dictionary<TKey,TValue>.
- context
- StreamingContext
Uma StreamingContext estrutura contendo a origem e o destino do fluxo serializado associado ao Dictionary<TKey,TValue>.
Observações
Este construtor é chamado durante a desserialização para reconstituir um objeto transmitido sobre um fluxo. Para mais informações, consulte XML e Serialização SOAP.