SortedList<TKey,TValue> Constructeurs

Définition

Initialise une nouvelle instance de la classe SortedList<TKey,TValue>.

Surcharges

SortedList<TKey,TValue>()

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IComparer<T> par défaut.

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IComparer<T> spécifié.

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié, possède une capacité suffisante pour accepter le nombre d'éléments copiés et utilise le IComparer<T> par défaut.

SortedList<TKey,TValue>(Int32)

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IComparer<T> par défaut.

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié, possède une capacité suffisante pour accepter le nombre d'éléments copiés et utilise le IComparer<T> spécifié.

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IComparer<T> spécifié.

SortedList<TKey,TValue>()

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IComparer<T> par défaut.

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

Exemples

L’exemple de code suivant crée un vide SortedList<TKey,TValue> de chaînes avec des clés de chaîne et utilise la Add méthode pour ajouter des éléments. L’exemple montre que la Add méthode lève un ArgumentException lors de la tentative d’ajout d’une clé en double.

Cet exemple de code fait partie d’un exemple plus grand fourni pour 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."

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur par défaut.

Ce constructeur utilise la valeur par défaut pour la capacité initiale du SortedList<TKey,TValue>. Pour définir la capacité initiale, utilisez le SortedList<TKey,TValue>(Int32) constructeur. Si la taille finale de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au SortedList<TKey,TValue>.

Ce constructeur utilise le comparateur par défaut pour TKey. Pour spécifier un comparateur, utilisez le SortedList<TKey,TValue>(IComparer<TKey>) constructeur. Le comparateur Comparer<T>.Default par défaut vérifie si le type TKey de clé implémente System.IComparable<T> et utilise cette implémentation, si disponible. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type de TKey clé implémente System.IComparable. Si le type TKey de clé n’implémente pas l’une ou l’autre interface, vous pouvez spécifier une System.Collections.Generic.IComparer<T> implémentation dans une surcharge de constructeur qui accepte un comparer paramètre.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

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

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale par défaut et utilise le IComparer<T> spécifié.

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

Paramètres

comparer
IComparer<TKey>

Implémentation de IComparer<T> à utiliser lors de la comparaison de clés.

- ou -

null pour utiliser Comparer<T> par défaut pour le type de la clé.

Exemples

L’exemple de code suivant crée une liste triée avec un comparateur qui ne respecte pas la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des touches minuscules et d’autres avec des touches majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par la casse, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple montre comment afficher les éléments dans un ordre de tri qui ne respecte pas la casse.

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

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur spécifié.

Ce constructeur utilise la valeur par défaut pour la capacité initiale du SortedList<TKey,TValue>. Pour définir la capacité initiale, utilisez le SortedList<TKey,TValue>(Int32, IComparer<TKey>) constructeur. Si la taille finale de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au SortedList<TKey,TValue>.

Ce constructeur est une opération O(1).

Voir aussi

S’applique à

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

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié, possède une capacité suffisante pour accepter le nombre d'éléments copiés et utilise le IComparer<T> par défaut.

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

Paramètres

dictionary
IDictionary<TKey,TValue>

IDictionary<TKey,TValue> dont les éléments sont copiés dans le nouveau SortedList<TKey,TValue>.

Exceptions

dictionary a la valeur null.

dictionary contient une ou plusieurs clés en double.

Exemples

L’exemple de code suivant montre comment utiliser SortedList<TKey,TValue> pour créer une copie triée des informations dans un Dictionary<TKey,TValue>, en passant le Dictionary<TKey,TValue> au SortedList<TKey,TValue>(IDictionary<TKey,TValue>) constructeur.

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

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur par défaut ; de même, chaque clé de la source dictionary doit également être unique en fonction du comparateur par défaut.

La capacité du nouveau SortedList<TKey,TValue> est définie sur le nombre d’éléments dans dictionary, de sorte qu’aucun redimensionnement n’a lieu pendant que la liste est remplie.

Ce constructeur utilise le comparateur par défaut pour TKey. Pour spécifier un comparateur, utilisez le SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) constructeur. Le comparateur Comparer<T>.Default par défaut vérifie si le type TKey de clé implémente System.IComparable<T> et utilise cette implémentation, si disponible. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type de TKey clé implémente System.IComparable. Si le type TKey de clé n’implémente pas l’une ou l’autre interface, vous pouvez spécifier une System.Collections.Generic.IComparer<T> implémentation dans une surcharge de constructeur qui accepte un comparer paramètre.

Les clés dans sont copiées dans dictionary le nouveau SortedList<TKey,TValue> et triées une fois, ce qui fait de ce constructeur une opération O(n journal n).

Voir aussi

S’applique à

SortedList<TKey,TValue>(Int32)

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IComparer<T> par défaut.

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)

Paramètres

capacity
Int32

Nombre initial d'éléments que SortedList<TKey,TValue> peut contenir.

Exceptions

capacity est inférieur à zéro.

Exemples

L’exemple de code suivant crée une liste triée avec une capacité initiale de 4 et la remplit avec 4 entrées.

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

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur par défaut.

La capacité d’un SortedList<TKey,TValue> correspond au nombre d’éléments que le SortedList<TKey,TValue> peut contenir avant le redimensionnement. À mesure que des éléments sont ajoutés à un SortedList<TKey,TValue>, la capacité est automatiquement augmentée en fonction des besoins en réaffectant le tableau interne.

Si la taille de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au SortedList<TKey,TValue>.

La capacité peut être réduite en appelant TrimExcess ou en définissant explicitement la Capacity propriété. La diminution de la capacité réalloue la mémoire et copie tous les éléments dans .SortedList<TKey,TValue>

Ce constructeur utilise le comparateur par défaut pour TKey. Pour spécifier un comparateur, utilisez le SortedList<TKey,TValue>(Int32, IComparer<TKey>) constructeur. Le comparateur Comparer<T>.Default par défaut vérifie si le type TKey de clé implémente System.IComparable<T> et utilise cette implémentation, si disponible. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type de TKey clé implémente System.IComparable. Si le type TKey de clé n’implémente pas l’une ou l’autre interface, vous pouvez spécifier une System.Collections.Generic.IComparer<T> implémentation dans une surcharge de constructeur qui accepte un comparer paramètre.

Ce constructeur est une opération O(n), où n est capacity.

Voir aussi

S’applique à

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

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui contient des éléments copiés à partir du IDictionary<TKey,TValue> spécifié, possède une capacité suffisante pour accepter le nombre d'éléments copiés et utilise le IComparer<T> spécifié.

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

Paramètres

dictionary
IDictionary<TKey,TValue>

IDictionary<TKey,TValue> dont les éléments sont copiés dans le nouveau SortedList<TKey,TValue>.

comparer
IComparer<TKey>

Implémentation de IComparer<T> à utiliser lors de la comparaison de clés.

- ou -

null pour utiliser Comparer<T> par défaut pour le type de la clé.

Exceptions

dictionary a la valeur null.

dictionary contient une ou plusieurs clés en double.

Exemples

L’exemple de code suivant montre comment utiliser SortedList<TKey,TValue> pour créer une copie triée sans respect de la casse des informations dans un fichier qui ne respecte Dictionary<TKey,TValue>pas la casse , en passant le Dictionary<TKey,TValue> au SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) constructeur. Dans cet exemple, les comparateurs qui ne respectent pas la casse sont destinés à la culture actuelle.

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

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur spécifié ; de même, chaque clé de la source dictionary doit également être unique en fonction du comparateur spécifié.

La capacité du nouveau SortedList<TKey,TValue> est définie sur le nombre d’éléments dans dictionary, de sorte qu’aucun redimensionnement n’a lieu pendant que la liste est remplie.

Les clés dans sont copiées dans dictionary le nouveau SortedList<TKey,TValue> et triées une fois, ce qui fait de ce constructeur une opération O(n journal n).

Voir aussi

S’applique à

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

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

Initialise une nouvelle instance de la classe SortedList<TKey,TValue> qui est vide, possède la capacité initiale spécifiée et utilise le IComparer<T> spécifié.

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

Paramètres

capacity
Int32

Nombre initial d'éléments que SortedList<TKey,TValue> peut contenir.

comparer
IComparer<TKey>

Implémentation de IComparer<T> à utiliser lors de la comparaison de clés.

- ou -

null pour utiliser Comparer<T> par défaut pour le type de la clé.

Exceptions

capacity est inférieur à zéro.

Exemples

L’exemple de code suivant crée une liste triée avec une capacité initiale de 5 et un comparateur respectant la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des touches minuscules et d’autres avec des touches majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par la casse, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple montre comment afficher les éléments dans un ordre de tri qui ne respecte pas la casse.

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

Remarques

Chaque clé d’un SortedList<TKey,TValue> doit être unique en fonction du comparateur spécifié.

La capacité d’un SortedList<TKey,TValue> correspond au nombre d’éléments que le SortedList<TKey,TValue> peut contenir avant le redimensionnement. À mesure que des éléments sont ajoutés à un SortedList<TKey,TValue>, la capacité est automatiquement augmentée en fonction des besoins en réaffectant le tableau interne.

Si la taille de la collection peut être estimée, la spécification de la capacité initiale élimine la nécessité d’effectuer un certain nombre d’opérations de redimensionnement tout en ajoutant des éléments au SortedList<TKey,TValue>.

La capacité peut être réduite en appelant TrimExcess ou en définissant explicitement la Capacity propriété. La diminution de la capacité réalloue la mémoire et copie tous les éléments dans .SortedList<TKey,TValue>

Ce constructeur est une opération O(n), où n est capacity.

Voir aussi

S’applique à