Dictionary<TKey,TValue> Konstruktory

Definice

Inicializuje novou instanci Dictionary<TKey,TValue> třídy.

Přetížení

Name Description
Dictionary<TKey,TValue>()

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má výchozí počáteční kapacitu a používá výchozí porovnávač rovnosti pro typ klíče.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného a IDictionary<TKey,TValue> používá výchozí porovnávač rovnosti pro typ klíče.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného IEnumerable<T>.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má výchozí počáteční kapacitu a používá zadanou IEqualityComparer<T>.

Dictionary<TKey,TValue>(Int32)

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má zadanou počáteční kapacitu a používá výchozí porovnávač rovnosti pro typ klíče.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného IDictionary<TKey,TValue> a používá zadané IEqualityComparer<T>.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného IEnumerable<T> a používá zadané IEqualityComparer<T>.

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má zadanou počáteční kapacitu a používá zadanou IEqualityComparer<T>.

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
Zastaralé.

Inicializuje novou instanci Dictionary<TKey,TValue> třídy serializovanými daty.

Dictionary<TKey,TValue>()

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má výchozí počáteční kapacitu a používá výchozí porovnávač rovnosti pro typ klíče.

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

Příklady

Následující příklad kódu vytvoří prázdné Dictionary<TKey,TValue> řetězce s řetězcovými klíči a použije metodu Add k přidání některých prvků. Příklad ukazuje, že Add metoda vyvolá ArgumentException při pokusu o přidání duplicitního klíče.

Tento příklad kódu je součástí většího příkladu uvedeného pro třídu Dictionary<TKey,TValue>.

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

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

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

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

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

Poznámky

Každý klíč v rámci musí Dictionary<TKey,TValue> být jedinečný podle výchozího porovnávače rovnosti.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Tento konstruktor používá výchozí obecný porovnávač rovnosti , EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci. Alternativně můžete zadat implementaci IEqualityComparer<T> obecného rozhraní pomocí konstruktoru, který přijímá comparer parametr.

Poznámka:

Pokud můžete odhadnout velikost kolekce, pomocí konstruktoru, který určuje počáteční kapacitu, eliminuje nutnost provádět řadu operací změny velikosti při přidávání prvků do objektu Dictionary<TKey,TValue>.

Tento konstruktor je operace O(1).

Viz také

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného a IDictionary<TKey,TValue> používá výchozí porovnávač rovnosti pro typ klíče.

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

Parametry

dictionary
IDictionary<TKey,TValue>

Jejíž IDictionary<TKey,TValue> prvky jsou zkopírovány do nového Dictionary<TKey,TValue>.

Výjimky

dictionary je null.

dictionary obsahuje jeden nebo více duplicitních klíčů.

Příklady

Následující příklad kódu ukazuje, jak pomocí Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktoru inicializovat s seřazeným obsahem Dictionary<TKey,TValue> z jiného slovníku. Příklad kódu vytvoří SortedDictionary<TKey,TValue> a naplní data v náhodném pořadí a pak předá SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktoru a vytvoří seřazený Dictionary<TKey,TValue> objekt. To je užitečné, pokud potřebujete vytvořit seřazený slovník, který se v určitém okamžiku stane statickým; kopírování dat z objektu SortedDictionary<TKey,TValue> do vyšší Dictionary<TKey,TValue> rychlosti načítání.

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

Poznámky

Každý klíč v objektu Dictionary<TKey,TValue> musí být jedinečný podle výchozího porovnávače rovnosti. Stejně tak musí být každý klíč ve zdroji dictionary jedinečný také podle výchozího porovnávače rovnosti.

Počáteční kapacita nového Dictionary<TKey,TValue> je dostatečně velká, aby obsahovala všechny prvky v dictionary.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Tento konstruktor používá výchozí obecný porovnávač rovnosti , EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci. Alternativně můžete zadat implementaci IEqualityComparer<T> obecného rozhraní pomocí konstruktoru, který přijímá comparer parametr.

Tento konstruktor je operace O(n), kde n je počet prvků v dictionary.

Viz také

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného 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)))

Parametry

collection
IEnumerable<KeyValuePair<TKey,TValue>>

Jejíž IEnumerable<T> prvky jsou zkopírovány do nového Dictionary<TKey,TValue>.

Výjimky

collection je null.

collection obsahuje jeden nebo více duplicitních klíčů.

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má výchozí počáteční kapacitu a používá zadanou 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))

Parametry

comparer
IEqualityComparer<TKey>

Implementace IEqualityComparer<T> , která se má použít při porovnávání klíčů nebo null použití výchozí EqualityComparer<T> hodnoty pro typ klíče.

Příklady

Následující příklad kódu vytvoří porovnání Dictionary<TKey,TValue> rovnosti bez rozlišování malých a velkých písmen pro aktuální jazykovou verzi. Příklad přidá čtyři prvky, některé s klíči s velkými písmeny a některé s velkými písmeny. Příklad se pak pokusí přidat prvek s klíčem, který se liší od existujícího klíče pouze v případě, zachytí výslednou výjimku a zobrazí chybovou zprávu. Nakonec příklad zobrazí prvky ve slovníku.

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

Poznámky

Tento konstruktor použijte s porovnávači řetězců nerozlišující velká a malá písmena, které poskytuje StringComparer třída k vytvoření slovníků s klíči řetězce nerozlišující velká a malá písmena.

Každý klíč v určitém Dictionary<TKey,TValue> klíči musí být jedinečný podle zadaného porovnávače.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Pokud comparer je null, tento konstruktor používá výchozí obecný porovnávání rovnosti, EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci.

Poznámka:

Pokud můžete odhadnout velikost kolekce, pomocí konstruktoru, který určuje počáteční kapacitu, eliminuje nutnost provádět řadu operací změny velikosti při přidávání prvků do objektu Dictionary<TKey,TValue>.

Tento konstruktor je operace O(1).

Upozornění

Pokud capacity pochází ze vstupu uživatele, raději použijte konstruktor bez parametru kapacity a nechte kolekci změnit velikost při přidání prvků. Pokud musíte použít uživatelem zadanou hodnotu, buď ji uchytejte na rozumný limit (například) nebo ověřte, Math.Clamp(untrustedValue, 0, 20)že počet prvků odpovídá zadané hodnotě.

Viz také

Platí pro

Dictionary<TKey,TValue>(Int32)

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má zadanou počáteční kapacitu a používá výchozí porovnávač rovnosti pro typ klíče.

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)

Parametry

capacity
Int32

Počáteční počet prvků, které Dictionary<TKey,TValue> může obsahovat.

Výjimky

capacity je menší než 0.

Příklady

Následující příklad kódu vytvoří slovník s počáteční kapacitou 4 a naplní ho 4 položkami.

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

Poznámky

Každý klíč v rámci musí Dictionary<TKey,TValue> být jedinečný podle výchozího porovnávače rovnosti.

Kapacita je Dictionary<TKey,TValue> počet prvků, které lze přidat do Dictionary<TKey,TValue> před změnou velikosti nezbytné. Vzhledem k tomu, že jsou prvky přidány do objektu Dictionary<TKey,TValue>, kapacita se automaticky zvýší podle potřeby přidělením interního pole.

Pokud lze odhadnout velikost kolekce, určení počáteční kapacity eliminuje nutnost provádět několik operací změny velikosti při přidávání prvků do objektu Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Tento konstruktor používá výchozí obecný porovnávač rovnosti , EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci. Alternativně můžete zadat implementaci IEqualityComparer<T> obecného rozhraní pomocí konstruktoru, který přijímá comparer parametr.

Tento konstruktor je operace O(1).

Upozornění

Pokud capacity pochází ze vstupu uživatele, raději použijte konstruktor bez parametru kapacity a nechte kolekci změnit velikost při přidání prvků. Pokud musíte použít uživatelem zadanou hodnotu, buď ji uchytejte na rozumný limit (například) nebo ověřte, Math.Clamp(untrustedValue, 0, 20)že počet prvků odpovídá zadané hodnotě.

Viz také

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného IDictionary<TKey,TValue> a používá zadané 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))

Parametry

dictionary
IDictionary<TKey,TValue>

Jejíž IDictionary<TKey,TValue> prvky jsou zkopírovány do nového Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

Implementace IEqualityComparer<T> , která se má použít při porovnávání klíčů nebo null použití výchozí EqualityComparer<T> hodnoty pro typ klíče.

Výjimky

dictionary je null.

dictionary obsahuje jeden nebo více duplicitních klíčů.

Příklady

Následující příklad kódu ukazuje, jak pomocí Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktoru inicializovat Dictionary<TKey,TValue> s rozlišováním malých a velkých písmen seřazený obsah z jiného slovníku. Příklad kódu vytvoří SortedDictionary<TKey,TValue> porovnávač bez rozlišování velkých a malých písmen a naplní ho daty v náhodném pořadí a pak předá SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktoru společně s porovnávačem rovnosti bez rozlišování malých a velkých písmen a vytvoří seřazený Dictionary<TKey,TValue> objekt. To je užitečné, pokud potřebujete vytvořit seřazený slovník, který se v určitém okamžiku stane statickým; kopírování dat z objektu SortedDictionary<TKey,TValue> do vyšší Dictionary<TKey,TValue> rychlosti načítání.

Poznámka:

Když vytvoříte nový slovník bez rozlišování velkých a malých písmen a naplníte ho položkami ze slovníku, který používá porovnávač rozlišující malá a velká písmena, jako v tomto příkladu, dojde k výjimce, pokud vstupní slovník obsahuje klíče, které se liší pouze v případě, že se liší pouze v případě.

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

Poznámky

Tento konstruktor použijte s porovnávači řetězců nerozlišující velká a malá písmena, které poskytuje StringComparer třída k vytvoření slovníků s klíči řetězce nerozlišující velká a malá písmena.

Každý klíč v objektu Dictionary<TKey,TValue> musí být jedinečný podle zadaného porovnávače. Stejně tak musí být každý klíč ve zdroji dictionary jedinečný také podle zadaného porovnávače.

Poznámka:

Duplicitní klíče mohou nastat například v případě, že comparer je jedním z porovnávačů řetězců nerozlišující velká a malá písmena, které poskytuje StringComparer třída a dictionary nepoužívá klíč porovnávače nerozlišující malá a velká písmena.

Počáteční kapacita nového Dictionary<TKey,TValue> je dostatečně velká, aby obsahovala všechny prvky v dictionary.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Pokud comparer je null, tento konstruktor používá výchozí obecný porovnávání rovnosti, EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci.

Tento konstruktor je operace O(n), kde n je počet prvků v dictionary.

Viz také

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která obsahuje prvky zkopírované ze zadaného IEnumerable<T> a používá zadané 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))

Parametry

collection
IEnumerable<KeyValuePair<TKey,TValue>>

Jejíž IEnumerable<T> prvky jsou zkopírovány do nového Dictionary<TKey,TValue>.

comparer
IEqualityComparer<TKey>

Implementace IEqualityComparer<T> , která se má použít při porovnávání klíčů nebo null použití výchozí EqualityComparer<T> hodnoty pro typ klíče.

Výjimky

collection je null.

collection obsahuje jeden nebo více duplicitních klíčů.

Platí pro

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

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Inicializuje novou instanci Dictionary<TKey,TValue> třídy, která je prázdná, má zadanou počáteční kapacitu a používá zadanou 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))

Parametry

capacity
Int32

Počáteční počet prvků, které Dictionary<TKey,TValue> může obsahovat.

comparer
IEqualityComparer<TKey>

Implementace IEqualityComparer<T> , která se má použít při porovnávání klíčů nebo null použití výchozí EqualityComparer<T> hodnoty pro typ klíče.

Výjimky

capacity je menší než 0.

Příklady

Následující příklad kódu vytvoří Dictionary<TKey,TValue> s počáteční kapacitou 5 a porovnání rovnosti bez rozlišování malých a malých písmen pro aktuální jazykovou verzi. Příklad přidá čtyři prvky, některé s klíči s velkými písmeny a některé s velkými písmeny. Příklad se pak pokusí přidat prvek s klíčem, který se liší od existujícího klíče pouze v případě, zachytí výslednou výjimku a zobrazí chybovou zprávu. Nakonec příklad zobrazí prvky ve slovníku.

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

Poznámky

Tento konstruktor použijte s porovnávači řetězců nerozlišující velká a malá písmena, které poskytuje StringComparer třída k vytvoření slovníků s klíči řetězce nerozlišující velká a malá písmena.

Každý klíč v určitém Dictionary<TKey,TValue> klíči musí být jedinečný podle zadaného porovnávače.

Kapacita je Dictionary<TKey,TValue> počet prvků, které lze přidat do Dictionary<TKey,TValue> před změnou velikosti nezbytné. Vzhledem k tomu, že jsou prvky přidány do objektu Dictionary<TKey,TValue>, kapacita se automaticky zvýší podle potřeby přidělením interního pole.

Pokud lze odhadnout velikost kolekce, určení počáteční kapacity eliminuje nutnost provádět několik operací změny velikosti při přidávání prvků do objektu Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> vyžaduje implementaci rovnosti, aby bylo možné určit, zda jsou klíče stejné. Pokud comparer je null, tento konstruktor používá výchozí obecný porovnávání rovnosti, EqualityComparer<T>.Default. Pokud typ TKey implementuje System.IEquatable<T> obecné rozhraní, použije výchozí porovnávač rovnosti tuto implementaci.

Tento konstruktor je operace O(1).

Viz také

Platí pro

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs
Zdroj:
Dictionary.cs

Upozornění

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

Inicializuje novou instanci Dictionary<TKey,TValue> třídy serializovanými daty.

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)

Parametry

info
SerializationInfo

Objekt SerializationInfo obsahující informace potřebné k serializaci objektu Dictionary<TKey,TValue>.

context
StreamingContext

Struktura StreamingContext obsahující zdroj a cíl serializovaného datového proudu přidruženého k Dictionary<TKey,TValue>.

Atributy

Poznámky

Tento konstruktor je volána během deserializace k rekonstituci objektu přenášeného přes proud. Další informace naleznete v tématu XML a SOAP Serializace.

Viz také

Platí pro