SortedList<TKey,TValue> Конструкторы

Определение

Инициализирует новый экземпляр класса SortedList<TKey,TValue>.

Перегрузки

SortedList<TKey,TValue>()

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с начальной емкостью по умолчанию, использующий интерфейс IComparer<T> по умолчанию.

SortedList<TKey,TValue>(IComparer<TKey>)

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с начальной емкостью по умолчанию, использующий указанную функцию сравнения IComparer<T>.

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

Инициализирует новый экземпляр SortedList<TKey,TValue>, содержащий элементы, скопированные из указанного словаря IDictionary<TKey,TValue>, обладающий емкостью, достаточной для того, чтобы вместить количество скопированных элементов, и использующий интерфейс IComparer<T> по умолчанию.

SortedList<TKey,TValue>(Int32)

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с указанной начальной емкостью, использующий интерфейс IComparer<T> по умолчанию.

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

Инициализирует новый экземпляр SortedList<TKey,TValue>, содержащий элементы, скопированные из указанного словаря IDictionary<TKey,TValue>, обладающий емкостью, достаточной для того, чтобы вместить количество скопированных элементов, и использующий указанный интерфейс IComparer<T>.

SortedList<TKey,TValue>(Int32, IComparer<TKey>)

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с заданной начальной емкостью, использующий указанную функцию сравнения IComparer<T>.

SortedList<TKey,TValue>()

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с начальной емкостью по умолчанию, использующий интерфейс IComparer<T> по умолчанию.

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

Примеры

В следующем примере кода создается пустая SortedList<TKey,TValue> строка со строковыми ключами и используется Add метод для добавления некоторых элементов. В примере показано, что Add метод вызывает исключение ArgumentException при попытке добавить повторяющийся ключ.

Этот пример входит в состав более крупного примера использования класса SortedList<TKey,TValue>.

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

// Add some elements to the list. 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 list.
try
{
    openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
    Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith =
    new SortedList<string, string>();

// Add some elements to the list. 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 list.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new sorted list of strings, with string 
' keys. 
Dim openWith As New SortedList(Of String, String)

' Add some elements to the list. 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 list.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// Create a new sorted list of strings, with string
// keys.
let openWith = SortedList<string, string>()

// Add some elements to the list. 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 list.
try
    openWith.Add("txt", "winword.exe");
with
    | :? ArgumentException ->
        printfn "An element with Key = \"txt\" already exists."

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с компаратором по умолчанию.

Этот конструктор использует значение по умолчанию для начальной емкости SortedList<TKey,TValue>. Чтобы задать начальную емкость, используйте SortedList<TKey,TValue>(Int32) конструктор . Если можно оценить окончательный размер коллекции, указание начальной емкости избавляет от необходимости выполнять ряд операций изменения размера при добавлении элементов в SortedList<TKey,TValue>.

Этот конструктор использует компаратор по умолчанию для TKey. Чтобы указать компаратор, используйте SortedList<TKey,TValue>(IComparer<TKey>) конструктор . Средство сравнения Comparer<T>.Default по умолчанию проверяет, реализует System.IComparable<T> ли тип TKey ключа и использует ли она, если она доступна. В противном случае проверяет, Comparer<T>.Default реализует System.IComparableли тип TKey ключа . Если тип TKey ключа не реализует ни один из интерфейсов, можно указать System.Collections.Generic.IComparer<T> реализацию в перегрузке конструктора, принимающей comparer параметр .

Этот конструктор является операцией O(1).

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

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

SortedList<TKey,TValue>(IComparer<TKey>)

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с начальной емкостью по умолчанию, использующий указанную функцию сравнения IComparer<T>.

public:
 SortedList(System::Collections::Generic::IComparer<TKey> ^ comparer);
public SortedList (System.Collections.Generic.IComparer<TKey> comparer);
public SortedList (System.Collections.Generic.IComparer<TKey>? comparer);
new System.Collections.Generic.SortedList<'Key, 'Value> : System.Collections.Generic.IComparer<'Key> -> System.Collections.Generic.SortedList<'Key, 'Value>
Public Sub New (comparer As IComparer(Of TKey))

Параметры

comparer
IComparer<TKey>

Реализация интерфейса IComparer<T>, используемая при сравнении ключей.

-или-

Значение null для использования класса Comparer<T> по умолчанию для данного типа ключа.

Примеры

В следующем примере кода создается отсортированный список с функцией сравнения без учета регистра для текущего языка и региональных параметров. В примере добавляются четыре элемента: некоторые с клавишами нижнего регистра, а некоторые с клавишами верхнего регистра. Затем в примере выполняется попытка добавить элемент с ключом, который отличается от существующего ключа только по регистру, перехватывает результирующее исключение и выводит сообщение об ошибке. Наконец, в примере элементы отображаются в порядке сортировки без учета регистра.

using System;
using System.Collections.Generic;

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

        // Add some elements to the list.
        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 sorted list.");
        }

        // List the contents of the sorted list.
        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 sorted list.

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 list of strings, with string keys and
        ' a case-insensitive comparer for the current culture.
        Dim openWith As New SortedList(Of String, String)( _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add some elements to the list. 
        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 sorted list.")
        End Try
        
        ' List the contents of the sorted list.
        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 sorted list.
'
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с указанным компаратором.

Этот конструктор использует значение по умолчанию для начальной емкости SortedList<TKey,TValue>. Чтобы задать начальную емкость, используйте SortedList<TKey,TValue>(Int32, IComparer<TKey>) конструктор . Если можно оценить окончательный размер коллекции, указание начальной емкости избавляет от необходимости выполнять ряд операций изменения размера при добавлении элементов в SortedList<TKey,TValue>.

Этот конструктор является операцией O(1).

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

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

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

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый экземпляр SortedList<TKey,TValue>, содержащий элементы, скопированные из указанного словаря IDictionary<TKey,TValue>, обладающий емкостью, достаточной для того, чтобы вместить количество скопированных элементов, и использующий интерфейс IComparer<T> по умолчанию.

public:
 SortedList(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary);
public SortedList (System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
new System.Collections.Generic.SortedList<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> -> System.Collections.Generic.SortedList<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue))

Параметры

dictionary
IDictionary<TKey,TValue>

Объект IDictionary<TKey,TValue>, элементы которого копируются в новый объект SortedList<TKey,TValue>.

Исключения

dictionary имеет значение null.

Параметр dictionary содержит один или более повторяющихся ключей.

Примеры

В следующем примере кода показано, как с помощью SortedList<TKey,TValue> создать отсортированную копию данных в объекте Dictionary<TKey,TValue>путем передачи Dictionary<TKey,TValue>SortedList<TKey,TValue>(IDictionary<TKey,TValue>) в конструктор .

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 SortedList of strings with string keys,
        // and initialize it with the contents of the Dictionary.
        SortedList<string, string> copy =
                  new SortedList<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 SortedList of strings with string keys, 
        ' and initialize it with the contents of the Dictionary.
        Dim copy As New SortedList(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

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с компаратором по умолчанию; аналогичным образом, каждый ключ в источнике dictionary также должен быть уникальным в соответствии с компаратором по умолчанию.

Для емкости нового SortedList<TKey,TValue> задается количество элементов в dictionary, поэтому изменение размера при заполнении списка не выполняется.

Этот конструктор использует компаратор по умолчанию для TKey. Чтобы указать компаратор, используйте SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) конструктор . Средство сравнения Comparer<T>.Default по умолчанию проверяет, реализует System.IComparable<T> ли тип TKey ключа и использует ли она, если она доступна. В противном случае проверяет, Comparer<T>.Default реализует System.IComparableли тип TKey ключа . Если тип TKey ключа не реализует ни один из интерфейсов, можно указать System.Collections.Generic.IComparer<T> реализацию в перегрузке конструктора, принимающей comparer параметр .

Ключи в копируются в dictionary новый SortedList<TKey,TValue> и сортируются один раз, что делает этот конструктор операцией O(n log n).

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

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

SortedList<TKey,TValue>(Int32)

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с указанной начальной емкостью, использующий интерфейс IComparer<T> по умолчанию.

public:
 SortedList(int capacity);
public SortedList (int capacity);
new System.Collections.Generic.SortedList<'Key, 'Value> : int -> System.Collections.Generic.SortedList<'Key, 'Value>
Public Sub New (capacity As Integer)

Параметры

capacity
Int32

Начальное количество элементов, которое может содержать коллекция SortedList<TKey,TValue>.

Исключения

Значение параметра capacity меньше нуля.

Примеры

В следующем примере кода создается отсортированный список с начальной емкостью 4 и заполняется 4 записями.

using System;
using System.Collections.Generic;

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

        // Add 4 elements to the list.
        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 sorted list.
        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 = 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 list of strings, with string keys and
        ' an initial capacity of 4.
        Dim openWith As New SortedList(Of String, String)(4)
        
        ' Add 4 elements to the list. 
        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 sorted list.
        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 = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с компаратором по умолчанию.

Емкость SortedList<TKey,TValue> — это количество элементов, которые могут храниться перед изменением SortedList<TKey,TValue> размера. При добавлении элементов в SortedList<TKey,TValue>емкость автоматически увеличивается при необходимости путем перераспределения внутреннего массива.

Если размер коллекции можно оценить, указание начальной емкости избавляет от необходимости выполнять ряд операций изменения размера при добавлении элементов в SortedList<TKey,TValue>.

Емкость можно уменьшить путем вызова TrimExcess или явного Capacity задания свойства. Уменьшение емкости перераспределяет память и копирует все элементы в SortedList<TKey,TValue>.

Этот конструктор использует компаратор по умолчанию для TKey. Чтобы указать компаратор, используйте SortedList<TKey,TValue>(Int32, IComparer<TKey>) конструктор . Средство сравнения Comparer<T>.Default по умолчанию проверяет, реализует System.IComparable<T> ли тип TKey ключа и использует ли она, если она доступна. В противном случае проверяет, Comparer<T>.Default реализует System.IComparableли тип TKey ключа . Если тип TKey ключа не реализует ни один из интерфейсов, можно указать System.Collections.Generic.IComparer<T> реализацию в перегрузке конструктора, принимающей comparer параметр .

Этот конструктор является операцией O(n), где ncapacity.

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

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

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

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый экземпляр SortedList<TKey,TValue>, содержащий элементы, скопированные из указанного словаря IDictionary<TKey,TValue>, обладающий емкостью, достаточной для того, чтобы вместить количество скопированных элементов, и использующий указанный интерфейс IComparer<T>.

public:
 SortedList(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IComparer<TKey> ^ comparer);
public SortedList (System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer);
public SortedList (System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IComparer<TKey>? comparer);
new System.Collections.Generic.SortedList<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IComparer<'Key> -> System.Collections.Generic.SortedList<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IComparer(Of TKey))

Параметры

dictionary
IDictionary<TKey,TValue>

Объект IDictionary<TKey,TValue>, элементы которого копируются в новый объект SortedList<TKey,TValue>.

comparer
IComparer<TKey>

Реализация интерфейса IComparer<T>, используемая при сравнении ключей.

-или-

Значение null для использования класса Comparer<T> по умолчанию для данного типа ключа.

Исключения

dictionary имеет значение null.

Параметр dictionary содержит один или более повторяющихся ключей.

Примеры

В следующем примере кода показано, как использовать SortedList<TKey,TValue> для создания сортируемой копии данных без учета регистра в без учета регистра Dictionary<TKey,TValue>путем передачи Dictionary<TKey,TValue>SortedList<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");

        // Create a SortedList of strings with string keys and a
        // case-insensitive equality comparer for the current culture,
        // and initialize it with the contents of the Dictionary.
        SortedList<string, string> copy =
            new SortedList<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 = 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")
        
        ' Create a SortedList 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 SortedList(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 = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с указанным компаратором; аналогичным образом, каждый ключ в источнике dictionary также должен быть уникальным в соответствии с указанным компаратором.

Для емкости нового SortedList<TKey,TValue> задается количество элементов в dictionary, поэтому изменение размера при заполнении списка не выполняется.

Ключи в копируются в dictionary новый SortedList<TKey,TValue> и сортируются один раз, что делает этот конструктор операцией O(n log n).

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

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

SortedList<TKey,TValue>(Int32, IComparer<TKey>)

Исходный код:
SortedList.cs
Исходный код:
SortedList.cs
Исходный код:
SortedList.cs

Инициализирует новый пустой экземпляр класса SortedList<TKey,TValue> с заданной начальной емкостью, использующий указанную функцию сравнения IComparer<T>.

public:
 SortedList(int capacity, System::Collections::Generic::IComparer<TKey> ^ comparer);
public SortedList (int capacity, System.Collections.Generic.IComparer<TKey> comparer);
public SortedList (int capacity, System.Collections.Generic.IComparer<TKey>? comparer);
new System.Collections.Generic.SortedList<'Key, 'Value> : int * System.Collections.Generic.IComparer<'Key> -> System.Collections.Generic.SortedList<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IComparer(Of TKey))

Параметры

capacity
Int32

Начальное количество элементов, которое может содержать коллекция SortedList<TKey,TValue>.

comparer
IComparer<TKey>

Реализация интерфейса IComparer<T>, используемая при сравнении ключей.

-или-

Значение null для использования класса Comparer<T> по умолчанию для данного типа ключа.

Исключения

Значение параметра capacity меньше нуля.

Примеры

В следующем примере кода создается отсортированный список с начальной емкостью 5 и компаратором без учета регистра для текущего языка и региональных параметров. В примере добавляются четыре элемента: некоторые с клавишами нижнего регистра, а некоторые с клавишами верхнего регистра. Затем в примере выполняется попытка добавить элемент с ключом, который отличается от существующего ключа только по регистру, перехватывает результирующее исключение и выводит сообщение об ошибке. Наконец, в примере элементы отображаются в порядке сортировки без учета регистра.

using System;
using System.Collections.Generic;

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

        // Add 4 elements to the list.
        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 sorted list.");
        }

        // List the contents of the sorted list.
        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 sorted list.

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 list of strings, with string keys, an
        ' initial capacity of 5, and a case-insensitive comparer.
        Dim openWith As New SortedList(Of String, String)(5, _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add 4 elements to the list. 
        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 sorted list.")
        End Try
        
        ' List the contents of the sorted list.
        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 sorted list.
'
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

Комментарии

Каждый ключ в должен быть уникальным в SortedList<TKey,TValue> соответствии с указанным компаратором.

Емкость SortedList<TKey,TValue> — это количество элементов, которые могут храниться перед изменением SortedList<TKey,TValue> размера. При добавлении элементов в SortedList<TKey,TValue>емкость автоматически увеличивается при необходимости путем перераспределения внутреннего массива.

Если размер коллекции можно оценить, указание начальной емкости избавляет от необходимости выполнять ряд операций изменения размера при добавлении элементов в SortedList<TKey,TValue>.

Емкость можно уменьшить путем вызова TrimExcess или явного Capacity задания свойства. Уменьшение емкости перераспределяет память и копирует все элементы в SortedList<TKey,TValue>.

Этот конструктор является операцией O(n), где ncapacity.

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

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