SortedDictionary<TKey,TValue> Construtores

Definição

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe.

Sobrecargas

Name Description
SortedDictionary<TKey,TValue>()

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que está vazia e usa a implementação padrão IComparer<T> para o tipo de chave.

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que está vazia e utiliza a implementação especificada IComparer<T> para comparar chaves.

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e utiliza a implementação padrão IComparer<T> para o tipo de chave.

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e utiliza a implementação especificada IComparer<T> para comparar chaves.

SortedDictionary<TKey,TValue>()

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que está vazia e usa a implementação padrão IComparer<T> para o tipo de chave.

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

Exemplos

O exemplo de código seguinte cria um vazio SortedDictionary<TKey,TValue> de strings com chaves string e usa o Add método para adicionar alguns elementos. O exemplo demonstra que o Add método lança um ArgumentException ao tentar adicionar uma chave duplicada.

Este exemplo de código faz parte de um exemplo maior fornecido para a SortedDictionary<TKey,TValue> classe.

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

Observações

Cada chave em um SortedDictionary<TKey,TValue> deve ser única de acordo com o comparador padrão.

SortedDictionary<TKey,TValue> requer uma implementação de comparador para realizar comparações de chaves. Este construtor utiliza o comparador Comparer<T>.Defaultgenérico de igualdade por defeito . Se o tipo TKey implementar a System.IComparable<T> interface genérica, o comparador padrão usa essa implementação. Em alternativa, pode especificar uma implementação da IComparer<T> interface genérica usando um construtor que aceite um comparer parâmetro.

Este construtor é uma operação O(1).

Ver também

Aplica-se a

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que está vazia e utiliza a implementação especificada IComparer<T> para comparar chaves.

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>

A IComparer<T> implementação a usar ao comparar chaves, ou null usar o padrão Comparer<T> para o tipo da chave.

Exemplos

O exemplo de código seguinte cria um SortedDictionary<TKey,TValue> com um comparador insensível a maiúsculas e minúsculas para a cultura atual. O exemplo acrescenta quatro elementos, alguns com letras minúsculas e outros com maiúsculas. O exemplo tenta então adicionar um elemento com uma chave que difere de uma chave existente apenas por caso, apanha a exceção resultante e apresenta uma mensagem de erro. Finalmente, o exemplo mostra os elementos em ordem de ordenação insensível a maiúsculas e 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

Observações

Cada chave em um SortedDictionary<TKey,TValue> deve ser única de acordo com o comparador especificado.

SortedDictionary<TKey,TValue> requer uma implementação de comparador para realizar comparações de chaves. Se comparer for null, este construtor usa o comparador genérico de igualdade padrão, Comparer<T>.Default. Se o tipo TKey implementar a System.IComparable<T> interface genérica, o comparador padrão usa essa implementação.

Este construtor é uma operação O(1).

Ver também

Aplica-se a

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e utiliza a implementação padrão IComparer<T> para o tipo de chave.

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>

Os IDictionary<TKey,TValue> cujos elementos são copiados para o novo SortedDictionary<TKey,TValue>.

Exceções

dictionary é null.

dictionary contém uma ou mais chaves duplicadas.

Exemplos

O seguinte exemplo de código mostra como usar SortedDictionary<TKey,TValue> para criar uma cópia ordenada da informação num Dictionary<TKey,TValue>, passando o Dictionary<TKey,TValue> para o SortedDictionary<TKey,TValue>(IComparer<TKey>) construtor.

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

Observações

Cada chave em um SortedDictionary<TKey,TValue> deve ser única segundo o comparador padrão; portanto, cada chave na fonte dictionary também deve ser única segundo o comparador padrão.

SortedDictionary<TKey,TValue> requer uma implementação de comparador para realizar comparações de chaves. Este construtor utiliza o comparador de igualdade genérico por defeito, Comparer<T>.Default. Se o tipo TKey implementar a System.IComparable<T> interface genérica, o comparador padrão usa essa implementação. Em alternativa, pode especificar uma implementação da IComparer<T> interface genérica usando um construtor que aceite um comparer parâmetro.

Este construtor é uma operação O(n log ), onde n é o número de elementos em dictionaryn.

Ver também

Aplica-se a

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

Inicializa uma nova instância da SortedDictionary<TKey,TValue> classe que contém elementos copiados do especificado IDictionary<TKey,TValue> e utiliza a implementação especificada IComparer<T> para comparar chaves.

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>

Os IDictionary<TKey,TValue> cujos elementos são copiados para o novo SortedDictionary<TKey,TValue>.

comparer
IComparer<TKey>

A IComparer<T> implementação a usar ao comparar chaves, ou null usar o padrão Comparer<T> para o tipo da chave.

Exceções

dictionary é null.

dictionary contém uma ou mais chaves duplicadas.

Exemplos

O exemplo de código seguinte mostra como usar SortedDictionary<TKey,TValue> para criar uma cópia ordenada insensível a maiúsculas e minúsculas da informação num insensível Dictionary<TKey,TValue>a maiúsculas e maiúsculas , passando o Dictionary<TKey,TValue> para o SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) construtor. Neste exemplo, os comparadores insensíveis a maiúsculas minúsculas são para a cultura atual.

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

Observações

Cada chave em um SortedDictionary<TKey,TValue> deve ser única segundo o comparador especificado; portanto, cada chave na fonte dictionary também deve ser única segundo o comparador especificado.

SortedDictionary<TKey,TValue> requer uma implementação de comparador para realizar comparações de chaves. Se comparer for null, este construtor usa o comparador genérico de igualdade padrão, Comparer<T>.Default. Se o tipo TKey implementar a System.IComparable<T> interface genérica, o comparador padrão usa essa implementação.

Este construtor é uma operação O(n log ), onde n é o número de elementos em dictionaryn.

Ver também

Aplica-se a