Condividi tramite


SortedList<TKey,TValue> Costruttori

Definizione

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

Overload

Nome Descrizione
SortedList<TKey,TValue>()

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto predefinito IComparer<T>.

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

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto specificato IComparer<T>.

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

Inizializza una nuova istanza della SortedList<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue>, ha una capacità sufficiente per contenere il numero di elementi copiati e usa l'oggetto predefinito IComparer<T>.

SortedList<TKey,TValue>(Int32)

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto predefinito IComparer<T>.

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

Inizializza una nuova istanza della SortedList<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue>, ha una capacità sufficiente per contenere il numero di elementi copiati e usa l'oggetto specificato IComparer<T>.

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

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto specificato IComparer<T>.

SortedList<TKey,TValue>()

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto predefinito IComparer<T>.

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

Esempio

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

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

// 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto 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 è possibile stimare le dimensioni finali della raccolta, specificando la capacità iniziale è possibile eliminare la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta SortedList<TKey,TValue>di elementi a .

Questo costruttore usa l'operatore di confronto predefinito per TKey. Per specificare un operatore di confronto, usare il SortedList<TKey,TValue>(IComparer<TKey>) costruttore . L'operatore Comparer<T>.Default di confronto predefinito controlla se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default controlla 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>)

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale predefinita e usa l'oggetto specificato 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))

Parametri

comparer
IComparer<TKey>

Implementazione IComparer<T> da usare durante il confronto delle chiavi.

oppure

null per usare l'impostazione predefinita Comparer<T> per il tipo della chiave.

Esempio

Nell'esempio di codice seguente viene creato un elenco ordinato con un operatore di confronto 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. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, intercetta 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto 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 è possibile stimare le dimensioni finali della raccolta, specificando la capacità iniziale è possibile eliminare la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta SortedList<TKey,TValue>di elementi a .

Questo costruttore è un'operazione O(1).

Vedi anche

Si applica a

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

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue>, ha una capacità sufficiente per contenere il numero di elementi copiati e usa l'oggetto predefinito 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))

Parametri

dictionary
IDictionary<TKey,TValue>

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

Eccezioni

dictionary è null.

dictionary contiene una o più chiavi duplicate.

Esempio

Nell'esempio di codice seguente viene illustrato come usare SortedList<TKey,TValue> per creare 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto predefinito. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base all'operatore di confronto predefinito.

La capacità del nuovo SortedList<TKey,TValue> oggetto viene impostata sul numero di elementi in dictionary, quindi non viene eseguito alcun ridimensionamento durante il popolamento dell'elenco.

Questo costruttore usa l'operatore di confronto predefinito per TKey. Per specificare un operatore di confronto, usare il SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) costruttore . L'operatore Comparer<T>.Default di confronto predefinito controlla se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default controlla 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 nel nuovo SortedList<TKey,TValue> e ordinato una volta, che rende questo costruttore un'operazione O(n log n).

Vedi anche

Si applica a

SortedList<TKey,TValue>(Int32)

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto predefinito 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)

Parametri

capacity
Int32

Numero iniziale di elementi che l'oggetto SortedList<TKey,TValue> può contenere.

Eccezioni

capacity è minore di zero.

Esempio

L'esempio di codice seguente crea un elenco ordinato con una capacità iniziale pari a 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto predefinito.

La capacità di un SortedList<TKey,TValue> oggetto è il numero di elementi che l'oggetto SortedList<TKey,TValue> può contenere prima del ridimensionamento. Man mano che gli elementi vengono aggiunti a un SortedList<TKey,TValue>oggetto , la capacità viene aumentata automaticamente come richiesto dalla riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, la specifica della capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi a 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 l'operatore di confronto predefinito per TKey. Per specificare un operatore di confronto, usare il SortedList<TKey,TValue>(Int32, IComparer<TKey>) costruttore . L'operatore Comparer<T>.Default di confronto predefinito controlla se il tipo di TKey chiave implementa System.IComparable<T> e usa tale implementazione, se disponibile. In caso contrario, Comparer<T>.Default controlla 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>)

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe che contiene elementi copiati dall'oggetto specificato IDictionary<TKey,TValue>, ha una capacità sufficiente per contenere il numero di elementi copiati e usa l'oggetto specificato 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))

Parametri

dictionary
IDictionary<TKey,TValue>

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

comparer
IComparer<TKey>

Implementazione IComparer<T> da usare durante il confronto delle chiavi.

oppure

null per usare l'impostazione predefinita 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 usare SortedList<TKey,TValue> per creare una copia ordinata senza distinzione tra maiuscole e minuscole delle informazioni in un oggetto senza distinzione Dictionary<TKey,TValue>tra maiuscole e minuscole passando l'oggetto Dictionary<TKey,TValue> al SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) costruttore. In questo esempio, gli strumenti di confronto senza distinzione tra maiuscole e minuscole sono destinati alle 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto specificato. Analogamente, ogni chiave nell'origine dictionary deve essere univoca anche in base all'operatore di confronto specificato.

La capacità del nuovo SortedList<TKey,TValue> oggetto viene impostata sul numero di elementi in dictionary, quindi non viene eseguito alcun ridimensionamento durante il popolamento dell'elenco.

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

Vedi anche

Si applica a

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

Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs
Origine:
SortedList.cs

Inizializza una nuova istanza della SortedList<TKey,TValue> classe vuota, ha la capacità iniziale specificata e usa l'oggetto specificato 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))

Parametri

capacity
Int32

Numero iniziale di elementi che l'oggetto SortedList<TKey,TValue> può contenere.

comparer
IComparer<TKey>

Implementazione IComparer<T> da usare durante il confronto delle chiavi.

oppure

null per usare l'impostazione predefinita 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 pari a 5 e un operatore di confronto 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. L'esempio tenta quindi di aggiungere un elemento con una chiave diversa da una chiave esistente solo per caso, intercetta 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 di un SortedList<TKey,TValue> oggetto deve essere univoca in base all'operatore di confronto specificato.

La capacità di un SortedList<TKey,TValue> oggetto è il numero di elementi che l'oggetto SortedList<TKey,TValue> può contenere prima del ridimensionamento. Man mano che gli elementi vengono aggiunti a un SortedList<TKey,TValue>oggetto , la capacità viene aumentata automaticamente come richiesto dalla riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, la specifica della capacità iniziale elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi a 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