Compartir vía


SortedList<TKey,TValue> Constructores

Definición

Inicializa una nueva instancia de la clase SortedList<TKey,TValue>.

Sobrecargas

Nombre Description
SortedList<TKey,TValue>()

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial predeterminada y usa el valor predeterminado IComparer<T>.

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

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial predeterminada y usa el especificado IComparer<T>.

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

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que contiene elementos copiados del objeto especificado IDictionary<TKey,TValue>, tiene capacidad suficiente para acomodar el número de elementos copiados y usa el valor predeterminado IComparer<T>.

SortedList<TKey,TValue>(Int32)

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial especificada y usa el valor predeterminado IComparer<T>.

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

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que contiene elementos copiados de la clase especificada IDictionary<TKey,TValue>, tiene capacidad suficiente para acomodar el número de elementos copiados y usa el especificado IComparer<T>.

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

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial especificada y usa el especificado IComparer<T>.

SortedList<TKey,TValue>()

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial predeterminada y usa el valor predeterminado IComparer<T>.

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

Ejemplos

En el ejemplo de código siguiente se crea un vacío SortedList<TKey,TValue> de cadenas con claves de cadena y se usa el Add método para agregar algunos elementos. En el ejemplo se muestra que el Add método produce un ArgumentException al intentar agregar una clave duplicada.

Este ejemplo de código forma parte de un ejemplo más grande proporcionado para la SortedList<TKey,TValue> clase .

// 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."

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador predeterminado.

Este constructor usa el valor predeterminado para la capacidad inicial de SortedList<TKey,TValue>. Para establecer la capacidad inicial, use el SortedList<TKey,TValue>(Int32) constructor . Si se puede estimar el tamaño final de la colección, especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a SortedList<TKey,TValue>.

Este constructor usa el comparador predeterminado para TKey. Para especificar un comparador, use el SortedList<TKey,TValue>(IComparer<TKey>) constructor . El comparador Comparer<T>.Default predeterminado comprueba si el tipo TKey de clave implementa System.IComparable<T> y usa esa implementación, si está disponible. Si no es así, Comparer<T>.Default comprueba si el tipo TKey de clave implementa System.IComparable. Si el tipo TKey de clave no implementa ninguna interfaz, puede especificar una System.Collections.Generic.IComparer<T> implementación en una sobrecarga de constructor que acepte un comparer parámetro.

Este constructor es una operación de O(1).

Consulte también

Se aplica a

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

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial predeterminada y usa el especificado 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))

Parámetros

comparer
IComparer<TKey>

Implementación IComparer<T> que se va a usar al comparar claves.

O bien

null para usar el valor predeterminado Comparer<T> para el tipo de la clave.

Ejemplos

En el ejemplo de código siguiente se crea una lista ordenada con un comparador que no distingue mayúsculas de minúsculas para la referencia cultural actual. En el ejemplo se agregan cuatro elementos, algunos con claves en minúsculas y algunas con claves mayúsculas. A continuación, el ejemplo intenta agregar un elemento con una clave que difiere de una clave existente solo por caso, detecta la excepción resultante y muestra un mensaje de error. Por último, en el ejemplo se muestran los elementos en el criterio de ordenación sin distinción entre mayúsculas y minúsculas.

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

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador especificado.

Este constructor usa el valor predeterminado para la capacidad inicial de SortedList<TKey,TValue>. Para establecer la capacidad inicial, use el SortedList<TKey,TValue>(Int32, IComparer<TKey>) constructor . Si se puede estimar el tamaño final de la colección, especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a SortedList<TKey,TValue>.

Este constructor es una operación de O(1).

Consulte también

Se aplica a

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

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que contiene elementos copiados del objeto especificado IDictionary<TKey,TValue>, tiene capacidad suficiente para acomodar el número de elementos copiados y usa el valor predeterminado 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))

Parámetros

dictionary
IDictionary<TKey,TValue>

cuyos IDictionary<TKey,TValue> elementos se copian en el nuevo SortedList<TKey,TValue>.

Excepciones

dictionary es null.

dictionary contiene una o varias claves duplicadas.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar SortedList<TKey,TValue> para crear una copia ordenada de la información en un Dictionary<TKey,TValue>, pasando el Dictionary<TKey,TValue>SortedList<TKey,TValue>(IDictionary<TKey,TValue>) objeto al constructor .

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

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador predeterminado; del mismo modo, todas las claves del dictionary origen también deben ser únicas según el comparador predeterminado.

La capacidad del nuevo SortedList<TKey,TValue> se establece en el número de elementos de dictionary, por lo que no se realiza ningún cambio de tamaño mientras se rellena la lista.

Este constructor usa el comparador predeterminado para TKey. Para especificar un comparador, use el SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) constructor . El comparador Comparer<T>.Default predeterminado comprueba si el tipo TKey de clave implementa System.IComparable<T> y usa esa implementación, si está disponible. Si no es así, Comparer<T>.Default comprueba si el tipo TKey de clave implementa System.IComparable. Si el tipo TKey de clave no implementa ninguna interfaz, puede especificar una System.Collections.Generic.IComparer<T> implementación en una sobrecarga de constructor que acepte un comparer parámetro.

Las claves de dictionary se copian en el nuevo SortedList<TKey,TValue> y se ordenan una vez, lo que hace que este constructor sea una operación de registro nde O(n .

Consulte también

Se aplica a

SortedList<TKey,TValue>(Int32)

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial especificada y usa el valor predeterminado 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)

Parámetros

capacity
Int32

Número inicial de elementos que SortedList<TKey,TValue> puede contener.

Excepciones

capacity es menor que cero.

Ejemplos

En el ejemplo de código siguiente se crea una lista ordenada con una capacidad inicial de 4 y se rellena con 4 entradas.

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

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador predeterminado.

La capacidad de es SortedList<TKey,TValue> el número de elementos que SortedList<TKey,TValue> puede contener antes de cambiar el tamaño. A medida que se agregan elementos a , SortedList<TKey,TValue>la capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a SortedList<TKey,TValue>.

La capacidad se puede reducir llamando a TrimExcess o estableciendo la Capacity propiedad explícitamente. Al reducir la capacidad, se reasigna la memoria y se copian todos los elementos de SortedList<TKey,TValue>.

Este constructor usa el comparador predeterminado para TKey. Para especificar un comparador, use el SortedList<TKey,TValue>(Int32, IComparer<TKey>) constructor . El comparador Comparer<T>.Default predeterminado comprueba si el tipo TKey de clave implementa System.IComparable<T> y usa esa implementación, si está disponible. Si no es así, Comparer<T>.Default comprueba si el tipo TKey de clave implementa System.IComparable. Si el tipo TKey de clave no implementa ninguna interfaz, puede especificar una System.Collections.Generic.IComparer<T> implementación en una sobrecarga de constructor que acepte un comparer parámetro.

Este constructor es una operación O(n), donde n es capacity.

Consulte también

Se aplica a

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

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que contiene elementos copiados de la clase especificada IDictionary<TKey,TValue>, tiene capacidad suficiente para acomodar el número de elementos copiados y usa el especificado 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))

Parámetros

dictionary
IDictionary<TKey,TValue>

cuyos IDictionary<TKey,TValue> elementos se copian en el nuevo SortedList<TKey,TValue>.

comparer
IComparer<TKey>

Implementación IComparer<T> que se va a usar al comparar claves.

O bien

null para usar el valor predeterminado Comparer<T> para el tipo de la clave.

Excepciones

dictionary es null.

dictionary contiene una o varias claves duplicadas.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar SortedList<TKey,TValue> para crear una copia ordenada sin distinción entre mayúsculas y minúsculas de la información en un sin distinción entre mayúsculas y minúsculas Dictionary<TKey,TValue>pasando al SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)Dictionary<TKey,TValue> constructor . En este ejemplo, los comparadores que no distinguen mayúsculas de minúsculas son para la referencia cultural actual.

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

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador especificado; del mismo modo, todas las claves del dictionary origen también deben ser únicas según el comparador especificado.

La capacidad del nuevo SortedList<TKey,TValue> se establece en el número de elementos de dictionary, por lo que no se realiza ningún cambio de tamaño mientras se rellena la lista.

Las claves de dictionary se copian en el nuevo SortedList<TKey,TValue> y se ordenan una vez, lo que hace que este constructor sea una operación de registro nde O(n .

Consulte también

Se aplica a

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

Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs
Source:
SortedList.cs

Inicializa una nueva instancia de la SortedList<TKey,TValue> clase que está vacía, tiene la capacidad inicial especificada y usa el especificado 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))

Parámetros

capacity
Int32

Número inicial de elementos que SortedList<TKey,TValue> puede contener.

comparer
IComparer<TKey>

Implementación IComparer<T> que se va a usar al comparar claves.

O bien

null para usar el valor predeterminado Comparer<T> para el tipo de la clave.

Excepciones

capacity es menor que cero.

Ejemplos

En el ejemplo de código siguiente se crea una lista ordenada con una capacidad inicial de 5 y un comparador que no distingue mayúsculas de minúsculas para la referencia cultural actual. En el ejemplo se agregan cuatro elementos, algunos con claves en minúsculas y algunas con claves mayúsculas. A continuación, el ejemplo intenta agregar un elemento con una clave que difiere de una clave existente solo por caso, detecta la excepción resultante y muestra un mensaje de error. Por último, en el ejemplo se muestran los elementos en el criterio de ordenación sin distinción entre mayúsculas y minúsculas.

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

Comentarios

Cada clave de un SortedList<TKey,TValue> debe ser única según el comparador especificado.

La capacidad de es SortedList<TKey,TValue> el número de elementos que SortedList<TKey,TValue> puede contener antes de cambiar el tamaño. A medida que se agregan elementos a , SortedList<TKey,TValue>la capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, especificar la capacidad inicial elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos a SortedList<TKey,TValue>.

La capacidad se puede reducir llamando a TrimExcess o estableciendo la Capacity propiedad explícitamente. Al reducir la capacidad, se reasigna la memoria y se copian todos los elementos de SortedList<TKey,TValue>.

Este constructor es una operación O(n), donde n es capacity.

Consulte también

Se aplica a