Condividi tramite


Dictionary<TKey,TValue> Costruttori

Definizione

Inizializza una nuova istanza della classe Dictionary<TKey,TValue>.

Overload

Nome Descrizione
Dictionary<TKey,TValue>()

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue> e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IEnumerable<T>.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto specificato IEqualityComparer<T>.

Dictionary<TKey,TValue>(Int32)

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue> e utilizza l'oggetto specificato IEqualityComparer<T>.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IEnumerable<T> e utilizza l'oggetto specificato IEqualityComparer<T>.

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

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto specificato IEqualityComparer<T>.

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

Inizializza una nuova istanza della classe Dictionary<TKey,TValue> con dati serializzati.

Dictionary<TKey,TValue>()

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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

Esempio

Nell'esempio di codice seguente viene creato un vuoto Dictionary<TKey,TValue> di stringhe con chiavi stringa e viene usato il Add metodo per aggiungere alcuni elementi. Nell'esempio viene illustrato che il Add metodo genera un'eccezione ArgumentException quando si tenta di aggiungere una chiave duplicata.

Questo esempio di codice fa parte di un esempio più ampio fornito per la 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

Commenti

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto di uguaglianza predefinito.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione. In alternativa, è possibile specificare un'implementazione dell'interfaccia IEqualityComparer<T> generica usando un costruttore che accetta un comparer parametro.

Annotazioni

Se è possibile stimare le dimensioni della raccolta, l'uso di un costruttore che specifica la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Dictionary<TKey,TValue>di elementi a .

Questo costruttore è un'operazione O(1).

Vedi anche

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue> e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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

Parametri

dictionary
IDictionary<TKey,TValue>

Oggetto i IDictionary<TKey,TValue> cui elementi vengono copiati nel nuovo Dictionary<TKey,TValue>oggetto .

Eccezioni

dictionary è null.

dictionary contiene una o più chiavi duplicate.

Esempio

Nell'esempio di codice seguente viene illustrato come usare il Dictionary<TKey,TValue>(IEqualityComparer<TKey>) costruttore per inizializzare un Dictionary<TKey,TValue> oggetto con contenuto ordinato da un altro dizionario. L'esempio di codice crea un SortedDictionary<TKey,TValue> oggetto e lo popola con i dati in ordine casuale, quindi passa l'oggetto SortedDictionary<TKey,TValue> al Dictionary<TKey,TValue>(IEqualityComparer<TKey>) costruttore, creando un Dictionary<TKey,TValue> oggetto ordinato. Ciò è utile se è necessario creare un dizionario ordinato che a un certo punto diventa statico; la copia dei dati da a SortedDictionary<TKey,TValue> un Dictionary<TKey,TValue> oggetto migliora la velocità di recupero.

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

Commenti

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto di uguaglianza predefinito. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base all'operatore di confronto di uguaglianza predefinito.

La capacità iniziale del nuovo Dictionary<TKey,TValue> è sufficientemente grande da contenere tutti gli elementi in dictionary.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione. In alternativa, è possibile specificare un'implementazione dell'interfaccia IEqualityComparer<T> generica usando un costruttore che accetta un comparer parametro.

Questo costruttore è un'operazione O(n), dove n è il numero di elementi in dictionary.

Vedi anche

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato 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)))

Parametri

collection
IEnumerable<KeyValuePair<TKey,TValue>>

Oggetto i IEnumerable<T> cui elementi vengono copiati nel nuovo Dictionary<TKey,TValue>oggetto .

Eccezioni

collection è null.

collection contiene una o più chiavi duplicate.

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto specificato 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))

Parametri

comparer
IEqualityComparer<TKey>

Implementazione IEqualityComparer<T> da usare per il confronto delle chiavi o null per usare l'impostazione predefinita EqualityComparer<T> per il tipo di chiave.

Esempio

Nell'esempio di codice seguente viene creato un Dictionary<TKey,TValue> oggetto con un operatore di confronto di uguaglianza senza distinzione tra maiuscole e minuscole per le impostazioni cultura correnti. Nell'esempio vengono aggiunti quattro elementi, alcuni con chiavi minuscole e alcune con chiavi maiuscole. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, intercetta l'eccezione risultante e visualizza un messaggio di errore. Infine, nell'esempio vengono visualizzati gli elementi nel dizionario.

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

Commenti

Usare questo costruttore con gli strumenti di confronto di stringhe senza distinzione tra maiuscole e minuscole forniti dalla StringComparer classe per creare dizionari con chiavi stringa senza distinzione tra maiuscole e minuscole.

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto specificato.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Se comparer è null, questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione.

Annotazioni

Se è possibile stimare le dimensioni della raccolta, l'uso di un costruttore che specifica la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Dictionary<TKey,TValue>di elementi a .

Questo costruttore è un'operazione O(1).

Attenzione

Se capacity proviene dall'input dell'utente, preferire l'uso di un costruttore senza un parametro di capacità e lasciare che la raccolta venga ridimensionata man mano che vengono aggiunti elementi. Se è necessario usare un valore specificato dall'utente, bloccarlo a un limite ragionevole (ad esempio, Math.Clamp(untrustedValue, 0, 20)) o verificare che il numero di elementi corrisponda al valore specificato.

Vedi anche

Si applica a

Dictionary<TKey,TValue>(Int32)

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'operatore di confronto di uguaglianza predefinito per il tipo di chiave.

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)

Parametri

capacity
Int32

Numero iniziale di elementi che l'oggetto Dictionary<TKey,TValue> può contenere.

Eccezioni

capacity è minore di 0.

Esempio

L'esempio di codice seguente crea un dizionario con una capacità iniziale di 4 e lo popola con 4 voci.

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

Commenti

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto di uguaglianza predefinito.

La capacità di un Dictionary<TKey,TValue> è il numero di elementi che possono essere aggiunti a Dictionary<TKey,TValue> prima di ridimensionare è necessario. Man mano che gli elementi vengono aggiunti a un Dictionary<TKey,TValue>oggetto , la capacità viene aumentata automaticamente come richiesto dalla riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, la specifica della capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi a Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione. In alternativa, è possibile specificare un'implementazione dell'interfaccia IEqualityComparer<T> generica usando un costruttore che accetta un comparer parametro.

Questo costruttore è un'operazione O(1).

Attenzione

Se capacity proviene dall'input dell'utente, preferire l'uso di un costruttore senza un parametro di capacità e lasciare che la raccolta venga ridimensionata man mano che vengono aggiunti elementi. Se è necessario usare un valore specificato dall'utente, bloccarlo a un limite ragionevole (ad esempio, Math.Clamp(untrustedValue, 0, 20)) o verificare che il numero di elementi corrisponda al valore specificato.

Vedi anche

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue> e utilizza l'oggetto specificato 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))

Parametri

dictionary
IDictionary<TKey,TValue>

Oggetto i IDictionary<TKey,TValue> cui elementi vengono copiati nel nuovo Dictionary<TKey,TValue>oggetto .

comparer
IEqualityComparer<TKey>

Implementazione IEqualityComparer<T> da usare per il confronto delle chiavi o null per usare l'impostazione predefinita EqualityComparer<T> per il tipo di chiave.

Eccezioni

dictionary è null.

dictionary contiene una o più chiavi duplicate.

Esempio

Nell'esempio di codice seguente viene illustrato come usare il Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) costruttore per inizializzare un Dictionary<TKey,TValue> oggetto con contenuto ordinato senza distinzione tra maiuscole e minuscole da un altro dizionario. L'esempio di codice crea un SortedDictionary<TKey,TValue> oggetto con un operatore di confronto senza distinzione tra maiuscole e minuscole e lo popola con i dati in ordine casuale, quindi passa SortedDictionary<TKey,TValue> al costruttore, insieme a Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) un operatore di confronto di uguaglianza senza distinzione tra maiuscole e minuscole, creando un Dictionary<TKey,TValue> oggetto ordinato. Ciò è utile se è necessario creare un dizionario ordinato che a un certo punto diventa statico; la copia dei dati da a SortedDictionary<TKey,TValue> un Dictionary<TKey,TValue> oggetto migliora la velocità di recupero.

Annotazioni

Quando si crea un nuovo dizionario con un operatore di confronto senza distinzione tra maiuscole e minuscole e lo si popola con voci di un dizionario che usa un operatore di confronto con distinzione tra maiuscole e minuscole, come in questo esempio, si verifica un'eccezione se il dizionario di input contiene chiavi che differiscono solo per maiuscole e minuscole.

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

Commenti

Usare questo costruttore con gli strumenti di confronto di stringhe senza distinzione tra maiuscole e minuscole forniti dalla StringComparer classe per creare dizionari con chiavi stringa senza distinzione tra maiuscole e minuscole.

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto specificato. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base all'operatore di confronto specificato.

Annotazioni

Ad esempio, le chiavi duplicate possono verificarsi se comparer è uno degli strumenti di confronto tra stringhe senza distinzione tra maiuscole e minuscole forniti dalla StringComparer classe e non usa una chiave di confronto senza distinzione tra maiuscole e dictionary minuscole.

La capacità iniziale del nuovo Dictionary<TKey,TValue> è sufficientemente grande da contenere tutti gli elementi in dictionary.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Se comparer è null, questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione.

Questo costruttore è un'operazione O(n), dove n è il numero di elementi in dictionary.

Vedi anche

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IEnumerable<T> e utilizza l'oggetto specificato 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))

Parametri

collection
IEnumerable<KeyValuePair<TKey,TValue>>

Oggetto i IEnumerable<T> cui elementi vengono copiati nel nuovo Dictionary<TKey,TValue>oggetto .

comparer
IEqualityComparer<TKey>

Implementazione IEqualityComparer<T> da usare per il confronto delle chiavi o null per usare l'impostazione predefinita EqualityComparer<T> per il tipo di chiave.

Eccezioni

collection è null.

collection contiene una o più chiavi duplicate.

Si applica a

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

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Inizializza una nuova istanza della Dictionary<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto specificato 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))

Parametri

capacity
Int32

Numero iniziale di elementi che l'oggetto Dictionary<TKey,TValue> può contenere.

comparer
IEqualityComparer<TKey>

Implementazione IEqualityComparer<T> da usare per il confronto delle chiavi o null per usare l'impostazione predefinita EqualityComparer<T> per il tipo di chiave.

Eccezioni

capacity è minore di 0.

Esempio

Nell'esempio di codice seguente viene creato un Dictionary<TKey,TValue> oggetto con una capacità iniziale pari a 5 e un operatore di confronto di uguaglianza senza distinzione tra maiuscole e minuscole per le impostazioni cultura correnti. Nell'esempio vengono aggiunti quattro elementi, alcuni con chiavi minuscole e alcune con chiavi maiuscole. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, intercetta l'eccezione risultante e visualizza un messaggio di errore. Infine, nell'esempio vengono visualizzati gli elementi nel dizionario.

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

Commenti

Usare questo costruttore con gli strumenti di confronto di stringhe senza distinzione tra maiuscole e minuscole forniti dalla StringComparer classe per creare dizionari con chiavi stringa senza distinzione tra maiuscole e minuscole.

Ogni chiave di un Dictionary<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto specificato.

La capacità di un Dictionary<TKey,TValue> è il numero di elementi che possono essere aggiunti a Dictionary<TKey,TValue> prima di ridimensionare è necessario. Man mano che gli elementi vengono aggiunti a un Dictionary<TKey,TValue>oggetto , la capacità viene aumentata automaticamente come richiesto dalla riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, la specifica della capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi a Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> richiede un'implementazione di uguaglianza per determinare se le chiavi sono uguali. Se comparer è null, questo costruttore usa l'operatore di confronto di uguaglianza generico predefinito, EqualityComparer<T>.Default. Se il tipo TKey implementa l'interfaccia System.IEquatable<T> generica, l'operatore di confronto di uguaglianza predefinito usa tale implementazione.

Questo costruttore è un'operazione O(1).

Vedi anche

Si applica a

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs
Origine:
Dictionary.cs

Attenzione

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

Inizializza una nuova istanza della classe Dictionary<TKey,TValue> con dati serializzati.

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)

Parametri

info
SerializationInfo

Oggetto SerializationInfo contenente le informazioni necessarie per serializzare l'oggetto Dictionary<TKey,TValue>.

context
StreamingContext

Struttura StreamingContext contenente l'origine e la destinazione del flusso serializzato associato all'oggetto Dictionary<TKey,TValue>.

Attributi

Commenti

Questo costruttore viene chiamato durante la deserializzazione per ricostituire un oggetto trasmesso su un flusso. Per altre informazioni, vedere Serializzazione XML e SOAP.

Vedi anche

Si applica a