Dictionary<TKey,TValue> Konstruktory

Definicja

Inicjuje nowe wystąpienie klasy Dictionary<TKey,TValue>.

Przeciążenia

Dictionary<TKey,TValue>()

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma domyślną pojemność początkową i używa domyślnego modułu porównania równości dla typu klucza.

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> elementu i używa domyślnego porównania równości dla typu klucza.

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IEnumerable<T>elementu .

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma domyślną początkową pojemność i używa określonego IEqualityComparer<T>elementu .

Dictionary<TKey,TValue>(Int32)

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma określoną pojemność początkową i używa domyślnego porównania równości dla typu klucza.

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> obiektu i używa określonego IEqualityComparer<T>elementu .

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IEnumerable<T> obiektu i używa określonego IEqualityComparer<T>elementu .

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

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma określoną początkową pojemność i używa określonego IEqualityComparer<T>elementu .

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
Przestarzałe.

Inicjuje nowe wystąpienie klasy Dictionary<TKey,TValue> z zserializowanymi danymi.

Dictionary<TKey,TValue>()

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma domyślną pojemność początkową i używa domyślnego modułu porównania równości dla typu klucza.

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

Przykłady

Poniższy przykład kodu tworzy puste Dictionary<TKey,TValue> ciągi z kluczami ciągów i używa Add metody w celu dodania niektórych elementów. W przykładzie Add pokazano, że metoda zgłasza błąd ArgumentException podczas próby dodania zduplikowanego klucza.

Ten przykład kodu jest częścią większego przykładu udostępnionego Dictionary<TKey,TValue> dla klasy .

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

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

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

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

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

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

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

Uwagi

Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym porównywaniem równości.

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.

Uwaga

Jeśli można oszacować rozmiar kolekcji, przy użyciu konstruktora, który określa początkową pojemność eliminuje konieczność wykonywania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.

Ten konstruktor jest operacją O(1).

Zobacz też

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> elementu i używa domyślnego porównania równości dla typu klucza.

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>

Element IDictionary<TKey,TValue> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .

Wyjątki

dictionary to null.

dictionary zawiera co najmniej jeden zduplikowany klucz.

Przykłady

W poniższym przykładzie kodu pokazano, jak za pomocą konstruktora Dictionary<TKey,TValue>(IEqualityComparer<TKey>) zainicjować Dictionary<TKey,TValue> element z posortowaną zawartością z innego słownika. Przykładowy kod tworzy SortedDictionary<TKey,TValue> obiekt i wypełnia je danymi w kolejności losowej, a następnie przekazuje SortedDictionary<TKey,TValue> element do Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktora, tworząc Dictionary<TKey,TValue> posortowany obiekt . Jest to przydatne, jeśli trzeba utworzyć posortowany słownik, który w pewnym momencie staje się statyczny; kopiowanie danych z elementu SortedDictionary<TKey,TValue> do elementu Dictionary<TKey,TValue> zwiększa szybkość pobierania.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Uwagi

Każdy klucz w elemecie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym porównywaniem równości. Podobnie każdy klucz w źródle dictionary musi być również unikatowy zgodnie z domyślnym porównywaniem równości.

Początkowa pojemność nowego Dictionary<TKey,TValue> jest wystarczająco duża, aby zawierała wszystkie elementy w elemecie dictionary.

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.

Ten konstruktor jest operacją O(n), gdzie n jest liczbą elementów w .dictionary

Zobacz też

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IEnumerable<T>elementu .

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

Element IEnumerable<T> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .

Wyjątki

collection to null.

collection zawiera co najmniej jeden zduplikowany klucz.

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma domyślną początkową pojemność i używa określonego IEqualityComparer<T>elementu .

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>

Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.

Przykłady

Poniższy przykład kodu tworzy element Dictionary<TKey,TValue> z funkcją porównywania równości bez uwzględniania wielkości liter dla bieżącej kultury. W przykładzie dodano cztery elementy, niektóre z małymi literami i niektóre z wielkimi literami. Następnie próbuje dodać element z kluczem, który różni się od istniejącego klucza tylko według wielkości liter, przechwytuje wynikowy wyjątek i wyświetla komunikat o błędzie. Na koniec przykład wyświetla elementy w słowniku.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

BMP is already in the dictionary.

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Uwagi

Użyj tego konstruktora z modułami porównującymi ciągi bez uwzględniania wielkości liter dostarczonymi przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.

Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym modułem porównującym.

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Jeśli comparer parametr ma nullwartość , ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.

Uwaga

Jeśli można oszacować rozmiar kolekcji, przy użyciu konstruktora, który określa początkową pojemność eliminuje konieczność wykonywania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.

Ten konstruktor jest operacją O(1).

Zobacz też

Dotyczy

Dictionary<TKey,TValue>(Int32)

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma określoną pojemność początkową i używa domyślnego porównania równości dla typu klucza.

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

Początkowa liczba elementów, które Dictionary<TKey,TValue> mogą zawierać.

Wyjątki

capacity wartość jest mniejsza niż 0.

Przykłady

Poniższy przykład kodu tworzy słownik o początkowej pojemności 4 i wypełnia go 4 wpisami.

using System;
using System.Collections.Generic;

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

    End Sub

End Class

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

Uwagi

Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym porównywaniem równości.

Pojemność elementu Dictionary<TKey,TValue> to liczba elementów, które można dodać do elementu przed zmianą rozmiaru Dictionary<TKey,TValue> jest konieczna. W miarę Dictionary<TKey,TValue>dodawania elementów do obiektu pojemność jest automatycznie zwiększana zgodnie z wymaganiami przez przeniesienie tablicy wewnętrznej.

Jeśli można oszacować rozmiar kolekcji, określenie początkowej pojemności eliminuje konieczność wykonywania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.

Ten konstruktor jest operacją O(1).

Zobacz też

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> obiektu i używa określonego IEqualityComparer<T>elementu .

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>

Element IDictionary<TKey,TValue> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .

comparer
IEqualityComparer<TKey>

Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.

Wyjątki

dictionary to null.

dictionary zawiera co najmniej jeden zduplikowany klucz.

Przykłady

W poniższym przykładzie kodu pokazano, jak za pomocą konstruktora Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) zainicjować Dictionary<TKey,TValue> zawartość posortowaną bez uwzględniania wielkości liter z innego słownika. Przykładowy kod tworzy SortedDictionary<TKey,TValue> obiekt z funkcją porównującą bez uwzględniania wielkości liter i wypełnia je danymi w kolejności losowej, a następnie przekazuje SortedDictionary<TKey,TValue> element do Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktora wraz z funkcją porównywania równości bez uwzględniania wielkości liter, tworząc Dictionary<TKey,TValue> posortowaną wartość . Jest to przydatne, jeśli trzeba utworzyć posortowany słownik, który w pewnym momencie staje się statyczny; kopiowanie danych z elementu SortedDictionary<TKey,TValue> do elementu Dictionary<TKey,TValue> zwiększa szybkość pobierania.

Uwaga

Podczas tworzenia nowego słownika z modułem porównującym bez uwzględniania wielkości liter i wypełniania go wpisami ze słownika używającego porównania uwzględniającego wielkość liter, jak w tym przykładzie, występuje wyjątek, jeśli słownik wejściowy zawiera klucze, które różnią się tylko wielkością liter.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Uwagi

Użyj tego konstruktora z modułami porównującymi ciągi bez uwzględniania wielkości liter dostarczonymi przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.

Każdy klucz w elemecie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym modułem porównującym; podobnie każdy klucz w źródle dictionary musi być również unikatowy zgodnie z określonym modułem porównującym.

Uwaga

Na przykład zduplikowane klucze mogą wystąpić, jeśli comparer jest jednym z porównań ciągów bez uwzględniania wielkości liter dostarczonych przez StringComparer klasę i dictionary nie używa klucza porównującego bez uwzględniania wielkości liter.

Początkowa pojemność nowego Dictionary<TKey,TValue> jest wystarczająco duża, aby zawierała wszystkie elementy w elemecie dictionary.

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Jeśli comparer parametr ma nullwartość , ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.

Ten konstruktor jest operacją O(n), gdzie n jest liczbą elementów w .dictionary

Zobacz też

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy zawierające elementy skopiowane z określonej klasy IEnumerable<T> i używa określonego IEqualityComparer<T>elementu .

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

Których IEnumerable<T> elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .

comparer
IEqualityComparer<TKey>

Implementacja IEqualityComparer<T> do użycia podczas porównywania kluczy lub null użycia wartości domyślnej EqualityComparer<T> dla typu klucza.

Wyjątki

collection to null.

collection zawiera co najmniej jeden zduplikowany klucz.

Dotyczy

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

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy, która jest pusta, ma określoną pojemność początkową i używa określonego 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

Początkowa liczba elementów, które Dictionary<TKey,TValue> mogą zawierać.

comparer
IEqualityComparer<TKey>

Implementacja IEqualityComparer<T> do użycia podczas porównywania kluczy lub null użycia wartości domyślnej EqualityComparer<T> dla typu klucza.

Wyjątki

capacity wartość jest mniejsza niż 0.

Przykłady

Poniższy przykład kodu tworzy element Dictionary<TKey,TValue> z początkową pojemnością 5 i porównaniem równości bez uwzględniania wielkości liter dla bieżącej kultury. W przykładzie dodano cztery elementy, niektóre z małymi literami i niektóre z kluczami wielkie litery. Następnie przykład próbuje dodać element z kluczem, który różni się od istniejącego klucza tylko według wielkości liter, przechwytuje wynikowy wyjątek i wyświetla komunikat o błędzie. Na koniec przykład wyświetla elementy w słowniku.

using System;
using System.Collections.Generic;

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

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

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

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

/* This code example produces the following output:

BMP is already in the dictionary.

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

Public Class Example
    
    Public Shared Sub Main() 

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

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

    End Sub

End Class

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

Uwagi

Użyj tego konstruktora z analizatorami ciągów bez uwzględniania wielkości liter dostarczonych przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.

Każdy klucz w elemecie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym porównaniem.

Pojemność elementu Dictionary<TKey,TValue> to liczba elementów, które można dodać do elementu przed zmianą rozmiaru Dictionary<TKey,TValue> jest konieczne. W miarę dodawania elementów do obiektu Dictionary<TKey,TValue>pojemność jest automatycznie zwiększana zgodnie z wymaganiami przez przydział tablicy wewnętrznej.

Jeśli można oszacować rozmiar kolekcji, określenie początkowej pojemności eliminuje konieczność wykonania wielu operacji zmiany rozmiaru podczas dodawania elementów do Dictionary<TKey,TValue>elementu .

Dictionary<TKey,TValue> wymaga implementacji równości w celu określenia, czy klucze są równe. Jeśli comparer jest to null, ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.

Ten konstruktor jest operacją O(1).

Zobacz też

Dotyczy

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

Źródło:
Dictionary.cs
Źródło:
Dictionary.cs
Źródło:
Dictionary.cs

Przestroga

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

Inicjuje nowe wystąpienie klasy Dictionary<TKey,TValue> z zserializowanymi danymi.

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

Parametry

info
SerializationInfo

SerializationInfo Obiekt zawierający informacje wymagane do serializacji elementu Dictionary<TKey,TValue>.

context
StreamingContext

Struktura StreamingContext zawierająca źródło i miejsce docelowe serializowanego strumienia skojarzonego z elementem Dictionary<TKey,TValue>.

Atrybuty

Uwagi

Ten konstruktor jest wywoływany podczas deserializacji w celu odtworzenia obiektu przesyłanego przez strumień. Aby uzyskać więcej informacji, zobacz Serializacja XML i SOAP.

Zobacz też

Dotyczy