SortedDictionary<TKey,TValue> Конструкторы
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Инициализирует новый экземпляр класса SortedDictionary<TKey,TValue>.
Перегрузки
| Имя | Описание |
|---|---|
| SortedDictionary<TKey,TValue>() |
Инициализирует новый экземпляр SortedDictionary<TKey,TValue> класса, который пуст и использует реализацию по умолчанию IComparer<T> для типа ключа. |
| SortedDictionary<TKey,TValue>(IComparer<TKey>) |
Инициализирует новый экземпляр класса, пустого SortedDictionary<TKey,TValue> и использующего указанную IComparer<T> реализацию для сравнения ключей. |
| SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного SortedDictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует реализацию по умолчанию IComparer<T> для типа ключа. |
| SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного SortedDictionary<TKey,TValue> значения IDictionary<TKey,TValue> , и использует указанную IComparer<T> реализацию для сравнения ключей. |
SortedDictionary<TKey,TValue>()
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
Инициализирует новый экземпляр SortedDictionary<TKey,TValue> класса, который пуст и использует реализацию по умолчанию IComparer<T> для типа ключа.
public:
SortedDictionary();
public SortedDictionary();
Public Sub New ()
Примеры
В следующем примере кода создается пустая SortedDictionary<TKey,TValue> строка со строковыми ключами и используется Add метод для добавления некоторых элементов. В примере показано, что Add метод вызывает исключение ArgumentException при попытке добавить повторяющийся ключ.
Этот пример кода является частью более крупного примера, предоставленного для SortedDictionary<TKey,TValue> класса.
// Create a new sorted dictionary of strings, with string
// keys.
SortedDictionary<string, string> openWith =
new SortedDictionary<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 sorted dictionary of strings, with string
' keys.
Dim openWith As New SortedDictionary(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
Комментарии
Каждый ключ в объекте SortedDictionary<TKey,TValue> должен быть уникальным в соответствии с сравнивателем по умолчанию.
SortedDictionary<TKey,TValue> требует реализации сравнения ключей. В этом конструкторе используется средство Comparer<T>.Defaultсравнения универсального равенства по умолчанию. Если тип TKey реализует универсальный System.IComparable<T> интерфейс, средство сравнения по умолчанию использует такую реализацию. Кроме того, можно указать реализацию универсального IComparer<T> интерфейса с помощью конструктора, который принимает comparer параметр.
Этот конструктор является операцией O(1).
См. также раздел
Применяется к
SortedDictionary<TKey,TValue>(IComparer<TKey>)
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
Инициализирует новый экземпляр класса, пустого SortedDictionary<TKey,TValue> и использующего указанную IComparer<T> реализацию для сравнения ключей.
public:
SortedDictionary(System::Collections::Generic::IComparer<TKey> ^ comparer);
public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer);
public SortedDictionary(System.Collections.Generic.IComparer<TKey>? comparer);
new System.Collections.Generic.SortedDictionary<'Key, 'Value> : System.Collections.Generic.IComparer<'Key> -> System.Collections.Generic.SortedDictionary<'Key, 'Value>
Public Sub New (comparer As IComparer(Of TKey))
Параметры
- comparer
- IComparer<TKey>
Реализация, используемая IComparer<T> при сравнении ключей или null для использования по умолчанию Comparer<T> для типа ключа.
Примеры
В следующем примере кода создается SortedDictionary<TKey,TValue> без учета регистра для текущего языка и региональных параметров. В этом примере добавляются четыре элемента с ключами нижнего регистра и ключами верхнего регистра. Затем этот пример пытается добавить элемент с ключом, который отличается от существующего ключа только по регистру, перехватывает результирующее исключение и отображает сообщение об ошибке. Наконец, в примере отображаются элементы в порядке сортировки без учета регистра.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new SortedDictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
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");
// 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 = 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 SortedDictionary of strings, with string keys
' and a case-insensitive comparer for the current culture.
Dim openWith As New SortedDictionary(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 sorted 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 = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
Комментарии
Каждый ключ в объекте SortedDictionary<TKey,TValue> должен быть уникальным в соответствии с указанным сравнивателем.
SortedDictionary<TKey,TValue> требует реализации сравнения ключей. Если comparer это nullтак, этот конструктор использует универсальный компратор равенства по умолчанию. Comparer<T>.Default Если тип TKey реализует универсальный System.IComparable<T> интерфейс, средство сравнения по умолчанию использует такую реализацию.
Этот конструктор является операцией O(1).
См. также раздел
Применяется к
SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>)
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного SortedDictionary<TKey,TValue>IDictionary<TKey,TValue> , и использует реализацию по умолчанию IComparer<T> для типа ключа.
public:
SortedDictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary);
public SortedDictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
new System.Collections.Generic.SortedDictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> -> System.Collections.Generic.SortedDictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue))
Параметры
- dictionary
- IDictionary<TKey,TValue>
Элементы IDictionary<TKey,TValue> , элементы которых копируются в новые SortedDictionary<TKey,TValue>.
Исключения
dictionary равно null.
dictionary содержит один или несколько повторяющихся ключей.
Примеры
В следующем примере кода показано, SortedDictionary<TKey,TValue> как создать отсортированную копию информации в объекте Dictionary<TKey,TValue>, передав конструктору Dictionary<TKey,TValue>SortedDictionary<TKey,TValue>(IComparer<TKey>) .
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new Dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
new Dictionary<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 SortedDictionary of strings with string keys,
// and initialize it with the contents of the Dictionary.
SortedDictionary<string, string> copy =
new SortedDictionary<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 Dictionary of strings, with string
' keys.
Dim openWith As New Dictionary(Of 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 SortedDictionary of strings with string keys,
' and initialize it with the contents of the Dictionary.
Dim copy As New SortedDictionary(Of String, String)(openWith)
' List the sorted 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
Комментарии
Каждый ключ в SortedDictionary<TKey,TValue> объекте должен быть уникальным в соответствии с сравнивателем по умолчанию. Таким образом, каждый ключ в источнике dictionary должен быть уникальным в соответствии со стандартом сравнения.
SortedDictionary<TKey,TValue> требует реализации сравнения ключей. Этот конструктор использует средство Comparer<T>.Defaultсравнения универсального равенства по умолчанию. Если тип TKey реализует универсальный System.IComparable<T> интерфейс, средство сравнения по умолчанию использует такую реализацию. Кроме того, можно указать реализацию универсального IComparer<T> интерфейса с помощью конструктора, который принимает comparer параметр.
Этот конструктор — это операция O(n log n) , где n находится количество элементов в dictionary.
См. также раздел
Применяется к
SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
- Исходный код:
- SortedDictionary.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанного SortedDictionary<TKey,TValue> значения IDictionary<TKey,TValue> , и использует указанную IComparer<T> реализацию для сравнения ключей.
public:
SortedDictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IComparer<TKey> ^ comparer);
public SortedDictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer);
public SortedDictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IComparer<TKey>? comparer);
new System.Collections.Generic.SortedDictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IComparer<'Key> -> System.Collections.Generic.SortedDictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IComparer(Of TKey))
Параметры
- dictionary
- IDictionary<TKey,TValue>
Элементы IDictionary<TKey,TValue> , элементы которых копируются в новые SortedDictionary<TKey,TValue>.
- comparer
- IComparer<TKey>
Реализация, используемая IComparer<T> при сравнении ключей или null для использования по умолчанию Comparer<T> для типа ключа.
Исключения
dictionary равно null.
dictionary содержит один или несколько повторяющихся ключей.
Примеры
В следующем примере кода показано, как использовать SortedDictionary<TKey,TValue> для создания нечувствительной копии отсортированных регистра сведений в нечувствительном Dictionary<TKey,TValue>регистре путем передачи конструктору Dictionary<TKey,TValue>SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) . В этом примере нечувствительные сравнения регистра предназначены для текущего языка и региональных параметров.
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 equality 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");
// 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);
}
// Create a SortedDictionary of strings with string keys and a
// case-insensitive equality comparer for the current culture,
// and initialize it with the contents of the Dictionary.
SortedDictionary<string, string> copy =
new SortedDictionary<string, string>(openWith,
StringComparer.CurrentCultureIgnoreCase);
// List the sorted 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 = txt, Value = notepad.exe
Key = Bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
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 Dictionary of strings, with string keys and
' a case-insensitive equality 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")
' 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
' Create a SortedDictionary of strings with string keys and a
' case-insensitive equality comparer for the current culture,
' and initialize it with the contents of the Dictionary.
Dim copy As New SortedDictionary(Of String, String)(openWith, _
StringComparer.CurrentCultureIgnoreCase)
' List the sorted 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 = txt, Value = notepad.exe
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
Комментарии
Каждый ключ в объекте SortedDictionary<TKey,TValue> должен быть уникальным в соответствии с указанным сравнивателем. Поэтому каждый ключ в источнике dictionary также должен быть уникальным в соответствии с указанным сравнивателем.
SortedDictionary<TKey,TValue> требует реализации сравнения ключей. Если comparer это nullтак, этот конструктор использует универсальный компратор равенства по умолчанию. Comparer<T>.Default Если тип TKey реализует универсальный System.IComparable<T> интерфейс, средство сравнения по умолчанию использует такую реализацию.
Этот конструктор — это операция O(n log n) , где n находится количество элементов в dictionary.