Dictionary<TKey,TValue> Конструкторы
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Инициализирует новый экземпляр класса Dictionary<TKey,TValue>.
Перегрузки
| Имя | Описание |
|---|---|
| Dictionary<TKey,TValue>() |
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет начальную емкость по умолчанию и использует средство сравнения равенства по умолчанию для типа ключа. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует средство сравнения равенства по умолчанию для типа ключа. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) |
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который содержит элементы, скопированные из указанного IEnumerable<T>объекта. |
| Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет начальную емкость по умолчанию и использует указанный IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32) |
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет указанную начальную емкость и использует средство сравнения равенства по умолчанию для типа ключа. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует указанный IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IEnumerable<T> , и использует указанный IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет указанную начальную емкость и использует указанный IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
Устаревшие..
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса сериализованными данными. |
Dictionary<TKey,TValue>()
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет начальную емкость по умолчанию и использует средство сравнения равенства по умолчанию для типа ключа.
public:
Dictionary();
public Dictionary();
Public Sub New ()
Примеры
В следующем примере кода создается пустая Dictionary<TKey,TValue> строка со строковыми ключами и используется Add метод для добавления некоторых элементов. В примере показано, что Add метод вызывает исключение ArgumentException при попытке добавить повторяющийся ключ.
Этот пример кода является частью более крупного примера, предоставленного для 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.
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
Комментарии
Каждый ключ в объекте Dictionary<TKey,TValue> должен быть уникальным в соответствии с сравнивателем равенства по умолчанию.
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Этот конструктор использует средство EqualityComparer<T>.Defaultсравнения универсального равенства по умолчанию. Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию. Кроме того, можно указать реализацию универсального IEqualityComparer<T> интерфейса с помощью конструктора, который принимает comparer параметр.
Замечание
Если можно оценить размер коллекции, с помощью конструктора, указывающего начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него Dictionary<TKey,TValue>.
Этот конструктор является операцией O(1).
См. также раздел
Применяется к
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует средство сравнения равенства по умолчанию для типа ключа.
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))
Параметры
- dictionary
- IDictionary<TKey,TValue>
Элементы IDictionary<TKey,TValue> , элементы которых копируются в новые Dictionary<TKey,TValue>.
Исключения
dictionary равно null.
dictionary содержит один или несколько повторяющихся ключей.
Примеры
В следующем примере кода показано, как использовать Dictionary<TKey,TValue>(IEqualityComparer<TKey>) конструктор для инициализации Dictionary<TKey,TValue> с сортировкой содержимого из другого словаря. Пример кода создает SortedDictionary<TKey,TValue> и заполняет его данными в случайном порядке, а затем передает SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IEqualityComparer<TKey>) конструктору, создавая Dictionary<TKey,TValue> отсортированный объект. Это полезно, если вам нужно создать отсортированный словарь, который в какой-то момент становится статическим; Копирование данных из a SortedDictionary<TKey,TValue> в Dictionary<TKey,TValue> повышение скорости извлечения.
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
Комментарии
Каждый ключ в Dictionary<TKey,TValue> объекте должен быть уникальным в соответствии со средством сравнения равенства по умолчанию. Аналогичным образом, каждый ключ в источнике dictionary должен быть уникальным в соответствии с сравнивателем равенства по умолчанию.
Начальная емкость нового Dictionary<TKey,TValue> достаточно велика, чтобы содержать все элементы.dictionary
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Этот конструктор использует средство EqualityComparer<T>.Defaultсравнения универсального равенства по умолчанию. Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию. Кроме того, можно указать реализацию универсального IEqualityComparer<T> интерфейса с помощью конструктора, который принимает comparer параметр.
Этот конструктор является операцией O(n), где n — это количество элементов в dictionary.
См. также раздел
Применяется к
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который содержит элементы, скопированные из указанного 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)))
Параметры
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Элементы IEnumerable<T> , элементы которых копируются в новые Dictionary<TKey,TValue>.
Исключения
collection равно null.
collection содержит один или несколько повторяющихся ключей.
Применяется к
Dictionary<TKey,TValue>(IEqualityComparer<TKey>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет начальную емкость по умолчанию и использует указанный 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))
Параметры
- comparer
- IEqualityComparer<TKey>
Реализация, используемая IEqualityComparer<T> при сравнении ключей или null для использования по умолчанию EqualityComparer<T> для типа ключа.
Примеры
В следующем примере кода создается Dictionary<TKey,TValue> средство сравнения равенства без учета регистра для текущего языка и региональных параметров. В этом примере добавляются четыре элемента с ключами нижнего регистра и ключами верхнего регистра. Затем этот пример пытается добавить элемент с ключом, который отличается от существующего ключа только по регистру, перехватывает результирующее исключение и отображает сообщение об ошибке. Наконец, в примере отображаются элементы в словаре.
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
Комментарии
Используйте этот конструктор с нечувствительными строками сравнения регистров, предоставляемыми StringComparer классом, чтобы создавать словари с нечувствительными строковыми ключами регистра.
Каждый ключ в объекте Dictionary<TKey,TValue> должен быть уникальным в соответствии с указанным сравнивателем.
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Если comparer это nullтак, этот конструктор использует универсальный компратор равенства по умолчанию. EqualityComparer<T>.Default Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию.
Замечание
Если можно оценить размер коллекции, с помощью конструктора, указывающего начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него Dictionary<TKey,TValue>.
Этот конструктор является операцией O(1).
Предостережение
Если capacity поступает из ввода пользователем, предпочесть использовать конструктор без параметра емкости и разрешить коллекции изменять размер в виде элементов. Если необходимо использовать указанное пользователем значение, либо заклоните его в разумный предел (например, ) или убедитесь, Math.Clamp(untrustedValue, 0, 20)что число элементов соответствует указанному значению.
См. также раздел
Применяется к
Dictionary<TKey,TValue>(Int32)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет указанную начальную емкость и использует средство сравнения равенства по умолчанию для типа ключа.
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)
Параметры
- capacity
- Int32
Начальное число элементов, которые Dictionary<TKey,TValue> могут содержаться.
Исключения
capacity меньше 0.
Примеры
В следующем примере кода создается словарь с начальной емкостью 4 и заполняется 4 записями.
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
Комментарии
Каждый ключ в объекте Dictionary<TKey,TValue> должен быть уникальным в соответствии с сравнивателем равенства по умолчанию.
Емкость Dictionary<TKey,TValue> — это количество элементов, которые можно добавить в него Dictionary<TKey,TValue> перед изменением размера. Так как элементы добавляются в Dictionary<TKey,TValue>объект, емкость автоматически увеличивается при необходимости при перераспределении внутреннего массива.
Если размер коллекции можно оценить, указывая начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Этот конструктор использует средство EqualityComparer<T>.Defaultсравнения универсального равенства по умолчанию. Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию. Кроме того, можно указать реализацию универсального IEqualityComparer<T> интерфейса с помощью конструктора, который принимает comparer параметр.
Этот конструктор является операцией O(1).
Предостережение
Если capacity поступает из ввода пользователем, предпочесть использовать конструктор без параметра емкости и разрешить коллекции изменять размер в виде элементов. Если необходимо использовать указанное пользователем значение, либо заклоните его в разумный предел (например, ) или убедитесь, Math.Clamp(untrustedValue, 0, 20)что число элементов соответствует указанному значению.
См. также раздел
Применяется к
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует указанный 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))
Параметры
- dictionary
- IDictionary<TKey,TValue>
Элементы IDictionary<TKey,TValue> , элементы которых копируются в новые Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Реализация, используемая IEqualityComparer<T> при сравнении ключей или null для использования по умолчанию EqualityComparer<T> для типа ключа.
Исключения
dictionary равно null.
dictionary содержит один или несколько повторяющихся ключей.
Примеры
В следующем примере кода показано, как использовать Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) конструктор для инициализации Dictionary<TKey,TValue> с отсортированных по регистру сортированного содержимого из другого словаря. В примере кода создается SortedDictionary<TKey,TValue> нечувствительный метод сравнения регистра и заполняется данными в случайном порядке, а затем передается SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) конструктору вместе с нечувствительным сравнением равенства регистра, создавая Dictionary<TKey,TValue> отсортированный объект. Это полезно, если вам нужно создать отсортированный словарь, который в какой-то момент становится статическим; Копирование данных из a SortedDictionary<TKey,TValue> в Dictionary<TKey,TValue> повышение скорости извлечения.
Замечание
При создании словаря с нечувствительным методом сравнения регистра и заполнении его записями из словаря, использующего сопоставитель с учетом регистра, как в этом примере, исключение возникает, если входной словарь имеет ключи, которые отличаются только по регистру.
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
Комментарии
Используйте этот конструктор с нечувствительными строками сравнения регистров, предоставляемыми StringComparer классом, чтобы создавать словари с нечувствительными строковыми ключами регистра.
Каждый ключ в объекте Dictionary<TKey,TValue> должен быть уникальным в соответствии с указанным сравнивателем. Кроме того, каждый ключ в источнике dictionary должен быть уникальным в соответствии с указанным сравнивателем.
Замечание
Например, повторяющиеся ключи могут возникать, если comparer является одним из нечувствительных строковых сравнения регистров, предоставляемых StringComparer классом, и dictionary не используется нечувствительный ключ сравнения регистра.
Начальная емкость нового Dictionary<TKey,TValue> достаточно велика, чтобы содержать все элементы.dictionary
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Если comparer это nullтак, этот конструктор использует универсальный компратор равенства по умолчанию. EqualityComparer<T>.Default Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию.
Этот конструктор является операцией O(n), где n находится количество элементов в dictionary.
См. также раздел
Применяется к
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного Dictionary<TKey,TValue>IEnumerable<T> , и использует указанный 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))
Параметры
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Элементы IEnumerable<T> , элементы которых копируются в новые Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Реализация, используемая IEqualityComparer<T> при сравнении ключей или null для использования по умолчанию EqualityComparer<T> для типа ключа.
Исключения
collection равно null.
collection содержит один или несколько повторяющихся ключей.
Применяется к
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса, который является пустым, имеет указанную начальную емкость и использует указанный 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))
Параметры
- capacity
- Int32
Начальное число элементов, которые Dictionary<TKey,TValue> могут содержаться.
- comparer
- IEqualityComparer<TKey>
Реализация, используемая IEqualityComparer<T> при сравнении ключей или null для использования по умолчанию EqualityComparer<T> для типа ключа.
Исключения
capacity меньше 0.
Примеры
В следующем примере кода создается Dictionary<TKey,TValue> начальная емкость 5 и сравнение равенства без учета регистра для текущего языка и региональных параметров. В этом примере добавляются четыре элемента с ключами нижнего регистра и ключами верхнего регистра. Затем этот пример пытается добавить элемент с ключом, который отличается от существующего ключа только по регистру, перехватывает результирующее исключение и отображает сообщение об ошибке. Наконец, в примере отображаются элементы в словаре.
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
Комментарии
Используйте этот конструктор с нечувствительными строками сравнения регистров, предоставляемыми StringComparer классом, чтобы создавать словари с нечувствительными строковыми ключами регистра.
Каждый ключ в объекте Dictionary<TKey,TValue> должен быть уникальным в соответствии с указанным сравнивателем.
Емкость Dictionary<TKey,TValue> — это количество элементов, которые можно добавить в него Dictionary<TKey,TValue> перед изменением размера. Так как элементы добавляются в Dictionary<TKey,TValue>объект, емкость автоматически увеличивается при необходимости при перераспределении внутреннего массива.
Если размер коллекции можно оценить, указывая начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> требует реализации равенства, чтобы определить, равны ли ключи. Если comparer это nullтак, этот конструктор использует универсальный компратор равенства по умолчанию. EqualityComparer<T>.Default Если тип TKey реализует универсальный System.IEquatable<T> интерфейс, средство сравнения равенства по умолчанию использует такую реализацию.
Этот конструктор является операцией O(1).
См. также раздел
Применяется к
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
- Исходный код:
- Dictionary.cs
Внимание
This API supports obsolete formatter-based serialization. It should not be called or extended by application code.
Инициализирует новый экземпляр Dictionary<TKey,TValue> класса сериализованными данными.
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)
Параметры
- info
- SerializationInfo
SerializationInfo Объект, содержащий сведения, необходимые для сериализацииDictionary<TKey,TValue>.
- context
- StreamingContext
Структура StreamingContext , содержащая источник и назначение сериализованного потока, связанного с ним Dictionary<TKey,TValue>.
- Атрибуты
Комментарии
Этот конструктор вызывается во время десериализации, чтобы восстановить объект, передаваемый через поток. Дополнительные сведения см. в статье о сериализации XML и SOAP.