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<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<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<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 ), где n — количество элементов в dictionary.n

См. также раздел

Применяется к

SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)

Исходный код:
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 ), где n — количество элементов в dictionary.n

См. также раздел

Применяется к