SortedDictionary<TKey,TValue> Constructores

Definición

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

Sobrecargas

Nombre Description
SortedDictionary<TKey,TValue>()

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que está vacía y usa la implementación predeterminada IComparer<T> para el tipo de clave.

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que está vacía y usa la implementación especificada IComparer<T> para comparar las claves.

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que contiene elementos copiados del especificado IDictionary<TKey,TValue> y usa la implementación predeterminada IComparer<T> para el tipo de clave.

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que contiene elementos copiados del especificado y usa la implementación especificada IDictionary<TKey,TValue>IComparer<T> para comparar claves.

SortedDictionary<TKey,TValue>()

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que está vacía y usa la implementación predeterminada IComparer<T> para el tipo de clave.

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

Ejemplos

En el ejemplo de código siguiente se crea un vacío SortedDictionary<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 SortedDictionary<TKey,TValue> clase .

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

Comentarios

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

SortedDictionary<TKey,TValue> requiere una implementación del comparador para realizar comparaciones clave. Este constructor usa el comparador Comparer<T>.Defaultde igualdad genérico predeterminado. Si el tipo TKey implementa la System.IComparable<T> interfaz genérica, el comparador predeterminado usa esa implementación. Como alternativa, puede especificar una implementación de la IComparer<T> interfaz genérica mediante un constructor que acepte un comparer parámetro.

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

Consulte también

Se aplica a

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que está vacía y usa la implementación especificada IComparer<T> para comparar las claves.

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))

Parámetros

comparer
IComparer<TKey>

Implementación IComparer<T> que se va a usar al comparar claves o null usar el valor predeterminado Comparer<T> para el tipo de clave.

Ejemplos

En el ejemplo de código siguiente se crea un SortedDictionary<TKey,TValue> objeto 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 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

Comentarios

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

SortedDictionary<TKey,TValue> requiere una implementación del comparador para realizar comparaciones clave. Si comparer es null, este constructor usa el comparador de igualdad genérico predeterminado, Comparer<T>.Default. Si el tipo TKey implementa la System.IComparable<T> interfaz genérica, el comparador predeterminado usa esa implementación.

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

Consulte también

Se aplica a

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que contiene elementos copiados del especificado IDictionary<TKey,TValue> y usa la implementación predeterminada IComparer<T> para el tipo de clave.

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))

Parámetros

dictionary
IDictionary<TKey,TValue>

cuyos IDictionary<TKey,TValue> elementos se copian en el nuevo SortedDictionary<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 SortedDictionary<TKey,TValue> para crear una copia ordenada de la información en un Dictionary<TKey,TValue>, pasando el Dictionary<TKey,TValue>SortedDictionary<TKey,TValue>(IComparer<TKey>) 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 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

Comentarios

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

SortedDictionary<TKey,TValue> requiere una implementación del comparador para realizar comparaciones clave. Este constructor usa el comparador de igualdad genérico predeterminado, Comparer<T>.Default. Si el tipo TKey implementa la System.IComparable<T> interfaz genérica, el comparador predeterminado usa esa implementación. Como alternativa, puede especificar una implementación de la IComparer<T> interfaz genérica mediante un constructor que acepte un comparer parámetro.

Este constructor es una operación de O(n log ), donde n es el número de elementos de dictionaryn.

Consulte también

Se aplica a

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

Inicializa una nueva instancia de la SortedDictionary<TKey,TValue> clase que contiene elementos copiados del especificado y usa la implementación especificada IDictionary<TKey,TValue>IComparer<T> para comparar claves.

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))

Parámetros

dictionary
IDictionary<TKey,TValue>

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

comparer
IComparer<TKey>

Implementación IComparer<T> que se va a usar al comparar claves o null usar el valor predeterminado Comparer<T> para el tipo de 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 SortedDictionary<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 Dictionary<TKey,TValue>SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) 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");

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

Comentarios

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

SortedDictionary<TKey,TValue> requiere una implementación del comparador para realizar comparaciones clave. Si comparer es null, este constructor usa el comparador de igualdad genérico predeterminado, Comparer<T>.Default. Si el tipo TKey implementa la System.IComparable<T> interfaz genérica, el comparador predeterminado usa esa implementación.

Este constructor es una operación de O(n log ), donde n es el número de elementos de dictionaryn.

Consulte también

Se aplica a