SortedList<TKey,TValue> Costruttori

Definizione

Inizializza una nuova istanza della classe SortedList<TKey,TValue>.

Overload

SortedList<TKey,TValue>()

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Inizializza una nuova istanza della classe SortedList<TKey,TValue> che contiene gli elementi copiati dall'interfaccia IDictionary<TKey,TValue> specificata, la cui capacità è sufficiente a contenere il numero di elementi copiati e che usa l'interfaccia IComparer<T> predefinita.

SortedList<TKey,TValue>(Int32)

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Inizializza una nuova istanza della classe SortedList<TKey,TValue> che contiene gli elementi copiati dall'interfaccia IDictionary<TKey,TValue> specificata, la cui capacità è sufficiente a contenere il numero di elementi copiati e che usa l'interfaccia IComparer<T> specificata.

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

SortedList<TKey,TValue>()

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Esempio

Nell'esempio di codice seguente viene creato un vuoto SortedList<TKey,TValue> di stringhe con chiavi di stringa e viene usato il Add metodo per aggiungere alcuni elementi. Nell'esempio viene illustrato che il Add metodo genera un oggetto ArgumentException quando si tenta di aggiungere una chiave duplicata.

Questo esempio di codice fa parte di un esempio più grande fornito per la SortedList<TKey,TValue> classe.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer predefinito.

Questo costruttore usa il valore predefinito per la capacità iniziale di SortedList<TKey,TValue>. Per impostare la capacità iniziale, usare il SortedList<TKey,TValue>(Int32) costruttore. Se la dimensione finale della raccolta può essere stimata, specificando la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto SortedList<TKey,TValue>.

Questo costruttore usa il comparer predefinito per TKey. Per specificare un comparer, usare il SortedList<TKey,TValue>(IComparer<TKey>) costruttore. Il comparer Comparer<T>.Default predefinito verifica se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default verifica se il tipo di TKey chiave implementa System.IComparable. Se il tipo di TKey chiave non implementa alcuna interfaccia, è possibile specificare un'implementazione System.Collections.Generic.IComparer<T> in un overload del costruttore che accetta un comparer parametro.

Questo costruttore è un'operazione O(1).

Vedi anche

Si applica a

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

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Parametri

comparer
IComparer<TKey>

Implementazione di IComparer<T> da usare quando si confrontano le chiavi.

-oppure-

null per utilizzare l'oggetto Comparer<T> per il tipo della chiave.

Esempio

Nell'esempio di codice seguente viene creato un elenco ordinato con un comparer senza distinzione tra maiuscole e minuscole per le impostazioni cultura correnti. Nell'esempio vengono aggiunti quattro elementi, alcuni con chiavi minuscole e alcune con chiavi maiuscole e minuscole. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, rileva l'eccezione risultante e visualizza un messaggio di errore. Infine, nell'esempio vengono visualizzati gli elementi in ordine di ordinamento senza distinzione tra maiuscole e minuscole.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer specificato.

Questo costruttore usa il valore predefinito per la capacità iniziale di SortedList<TKey,TValue>. Per impostare la capacità iniziale, usare il SortedList<TKey,TValue>(Int32, IComparer<TKey>) costruttore. Se la dimensione finale della raccolta può essere stimata, specificando la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto SortedList<TKey,TValue>.

Questo costruttore è un'operazione O(1).

Vedi anche

Si applica a

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

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

Inizializza una nuova istanza della classe SortedList<TKey,TValue> che contiene gli elementi copiati dall'interfaccia IDictionary<TKey,TValue> specificata, la cui capacità è sufficiente a contenere il numero di elementi copiati e che usa l'interfaccia IComparer<T> predefinita.

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

Parametri

dictionary
IDictionary<TKey,TValue>

Oggetto IDictionary<TKey,TValue> i cui elementi sono copiati nel nuovo oggetto SortedList<TKey,TValue>.

Eccezioni

dictionary è null.

dictionary contiene una o più chiavi duplicate.

Esempio

Nell'esempio di codice seguente viene illustrato come creare SortedList<TKey,TValue> una copia ordinata delle informazioni in un Dictionary<TKey,TValue>oggetto , passando l'oggetto Dictionary<TKey,TValue> al SortedList<TKey,TValue>(IDictionary<TKey,TValue>) costruttore.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer predefinito. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base al comparer predefinito.

La capacità del nuovo SortedList<TKey,TValue> è impostata sul numero di elementi in dictionary, quindi non viene eseguito alcun ridimensionamento mentre l'elenco viene popolato.

Questo costruttore usa il comparer predefinito per TKey. Per specificare un comparer, usare il SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) costruttore. Il comparer Comparer<T>.Default predefinito verifica se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default verifica se il tipo di TKey chiave implementa System.IComparable. Se il tipo di TKey chiave non implementa alcuna interfaccia, è possibile specificare un'implementazione System.Collections.Generic.IComparer<T> in un overload del costruttore che accetta un comparer parametro.

Le chiavi in dictionary vengono copiate nella nuova SortedList<TKey,TValue> e ordinate una sola volta, che rende questo costruttore un'operazione O(n log n).

Vedi anche

Si applica a

SortedList<TKey,TValue>(Int32)

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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)

Parametri

capacity
Int32

Numero iniziale degli elementi che SortedList<TKey,TValue> può contenere.

Eccezioni

capacity è minore di zero.

Esempio

Nell'esempio di codice seguente viene creato un elenco ordinato con capacità iniziale di 4 e lo popola con 4 voci.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer predefinito.

La capacità di un SortedList<TKey,TValue> è il numero di elementi che possono SortedList<TKey,TValue> essere contenuti prima del ridimensionamento. Man mano che gli elementi vengono aggiunti a un SortedList<TKey,TValue>oggetto , la capacità viene aumentata automaticamente in base alla necessità di riallocare la matrice interna.

Se le dimensioni della raccolta possono essere stimate, specificando la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto SortedList<TKey,TValue>.

La capacità può essere ridotta chiamando TrimExcess o impostando la Capacity proprietà in modo esplicito. La riduzione della capacità rialloca la memoria e copia tutti gli elementi in SortedList<TKey,TValue>.

Questo costruttore usa il comparer predefinito per TKey. Per specificare un comparer, usare il SortedList<TKey,TValue>(Int32, IComparer<TKey>) costruttore. Il comparer Comparer<T>.Default predefinito verifica se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default verifica se il tipo di TKey chiave implementa System.IComparable. Se il tipo di TKey chiave non implementa alcuna interfaccia, è possibile specificare un'implementazione System.Collections.Generic.IComparer<T> in un overload del costruttore che accetta un comparer parametro.

Questo costruttore è un'operazione O(n), dove n è capacity.

Vedi anche

Si applica a

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

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

Inizializza una nuova istanza della classe SortedList<TKey,TValue> che contiene gli elementi copiati dall'interfaccia IDictionary<TKey,TValue> specificata, la cui capacità è sufficiente a contenere il numero di elementi copiati e che usa l'interfaccia IComparer<T> specificata.

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

Parametri

dictionary
IDictionary<TKey,TValue>

Oggetto IDictionary<TKey,TValue> i cui elementi sono copiati nel nuovo oggetto SortedList<TKey,TValue>.

comparer
IComparer<TKey>

Implementazione di IComparer<T> da usare quando si confrontano le chiavi.

-oppure-

null per utilizzare l'oggetto Comparer<T> per il tipo della chiave.

Eccezioni

dictionary è null.

dictionary contiene una o più chiavi duplicate.

Esempio

Nell'esempio di codice seguente viene illustrato come SortedList<TKey,TValue> creare una copia senza distinzione tra maiuscole e minuscole delle informazioni in caso Dictionary<TKey,TValue>di distinzione tra maiuscole e minuscole passando l'oggetto Dictionary<TKey,TValue> al SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) costruttore. In questo esempio, i comparer senza distinzione tra maiuscole e minuscole sono per le impostazioni cultura correnti.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer specificato. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base al comparer specificato.

La capacità del nuovo SortedList<TKey,TValue> è impostata sul numero di elementi in dictionary, quindi non viene eseguito alcun ridimensionamento mentre l'elenco viene popolato.

Le chiavi in dictionary vengono copiate nella nuova SortedList<TKey,TValue> e ordinate una sola volta, che rende questo costruttore un'operazione O(n log n).

Vedi anche

Si applica a

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

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

Inizializza una nuova istanza vuota della classe SortedList<TKey,TValue>, con la capacità iniziale predefinita e che usa l'interfaccia IComparer<T> specificata.

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

Parametri

capacity
Int32

Numero iniziale degli elementi che SortedList<TKey,TValue> può contenere.

comparer
IComparer<TKey>

Implementazione di IComparer<T> da usare quando si confrontano le chiavi.

-oppure-

null per utilizzare l'oggetto Comparer<T> per il tipo della chiave.

Eccezioni

capacity è minore di zero.

Esempio

Nell'esempio di codice seguente viene creato un elenco ordinato con capacità iniziale di 5 e un comparer senza distinzione tra maiuscole e minuscole per le impostazioni cultura correnti. Nell'esempio vengono aggiunti quattro elementi, alcuni con chiavi minuscole e alcune con chiavi maiuscole e minuscole. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, rileva l'eccezione risultante e visualizza un messaggio di errore. Infine, nell'esempio vengono visualizzati gli elementi in ordine di ordinamento senza distinzione tra maiuscole e minuscole.

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

Commenti

Ogni chiave in un SortedList<TKey,TValue> deve essere univoca in base al comparer specificato.

La capacità di un SortedList<TKey,TValue> è il numero di elementi che possono SortedList<TKey,TValue> essere contenuti prima del ridimensionamento. Man mano che gli elementi vengono aggiunti a un SortedList<TKey,TValue>oggetto , la capacità viene aumentata automaticamente in base alla necessità di riallocare la matrice interna.

Se le dimensioni della raccolta possono essere stimate, specificando la capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto SortedList<TKey,TValue>.

La capacità può essere ridotta chiamando TrimExcess o impostando la Capacity proprietà in modo esplicito. La riduzione della capacità rialloca la memoria e copia tutti gli elementi in SortedList<TKey,TValue>.

Questo costruttore è un'operazione O(n), dove n è capacity.

Vedi anche

Si applica a