Partager via


SortedList<TKey,TValue> Constructeurs

Définition

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

Surcharges

Nom Description
SortedList<TKey,TValue>()

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale par défaut et utilise la valeur par défaut IComparer<T>.

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

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

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément IDictionary<TKey,TValue>spécifié, dispose d’une capacité suffisante pour prendre en charge le nombre d’éléments copiés et utilise la valeur par défaut IComparer<T>.

SortedList<TKey,TValue>(Int32)

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

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément IDictionary<TKey,TValue>spécifié, dispose d’une capacité suffisante pour prendre en charge le nombre d’éléments copiés et utilise les éléments spécifiés IComparer<T>.

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale spécifiée et utilise la valeur spécifiée IComparer<T>.

SortedList<TKey,TValue>()

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale par défaut et utilise la valeur par défaut IComparer<T>.

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

Exemples

L’exemple de code suivant crée une chaîne vide SortedList<TKey,TValue> 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 une ArgumentException exception 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 =
    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 lors de l’ajout SortedList<TKey,TValue>d’éléments au .

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, le cas échéant. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type TKey de 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
Source:
SortedList.cs
Source:
SortedList.cs

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale par défaut et utilise la valeur spécifiée 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))

Paramètres

comparer
IComparer<TKey>

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

- ou -

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

Exemples

L’exemple de code suivant crée une liste triée avec un comparateur sans respect de la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des clés minuscules et certains avec des clés majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par cas, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments dans l’ordre de tri ne respectant 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 lors de l’ajout SortedList<TKey,TValue>d’éléments au .

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
Source:
SortedList.cs
Source:
SortedList.cs

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément IDictionary<TKey,TValue>spécifié, dispose d’une capacité suffisante pour prendre en charge le nombre d’éléments copiés et utilise la valeur par défaut 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))

Paramètres

dictionary
IDictionary<TKey,TValue>

Dont IDictionary<TKey,TValue> 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 dupliquées.

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>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, donc 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, le cas échéant. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type TKey de 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 contenues dictionary sont copiées dans le nouveau SortedList<TKey,TValue> et trié une fois, ce qui rend ce constructeur une opération O(n log n) .

Voir aussi

S’applique à

SortedList<TKey,TValue>(Int32)

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale spécifiée et utilise la valeur par défaut 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)

Paramètres

capacity
Int32

Nombre initial d’éléments que le SortedList<TKey,TValue> conteneur 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> est le nombre d’éléments qu’il SortedList<TKey,TValue> peut contenir avant le redimensionnement. À mesure que les éléments sont ajoutés à un SortedList<TKey,TValue>, la capacité est automatiquement augmentée 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 lors de l’ajout SortedList<TKey,TValue>d’éléments au .

La capacité peut être réduite en appelant TrimExcess ou en définissant explicitement la Capacity propriété. La réduction de la capacité réalloue la mémoire et copie tous les éléments dans le 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, le cas échéant. Si ce n’est pas le cas, Comparer<T>.Default vérifie si le type TKey de 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
Source:
SortedList.cs
Source:
SortedList.cs

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe qui contient des éléments copiés à partir de l’élément IDictionary<TKey,TValue>spécifié, dispose d’une capacité suffisante pour prendre en charge le nombre d’éléments copiés et utilise les éléments spécifiés 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))

Paramètres

dictionary
IDictionary<TKey,TValue>

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

comparer
IComparer<TKey>

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

- ou -

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

Exceptions

dictionary a la valeur null.

dictionary contient une ou plusieurs clés dupliquées.

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 une non-respect Dictionary<TKey,TValue>de la casse, en passant le Dictionary<TKey,TValue>SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) constructeur. Dans cet exemple, les comparateurs ne respectant pas la casse concernent 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, donc aucun redimensionnement n’a lieu pendant que la liste est remplie.

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

Voir aussi

S’applique à

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

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

Initialise une nouvelle instance de la SortedList<TKey,TValue> classe vide, a la capacité initiale spécifiée et utilise la valeur spécifiée 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))

Paramètres

capacity
Int32

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

comparer
IComparer<TKey>

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

- ou -

null pour utiliser la valeur par défaut Comparer<T> 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 ne respectant pas la casse pour la culture actuelle. L’exemple ajoute quatre éléments, certains avec des clés minuscules et certains avec des clés majuscules. L’exemple tente ensuite d’ajouter un élément avec une clé qui diffère d’une clé existante uniquement par cas, intercepte l’exception résultante et affiche un message d’erreur. Enfin, l’exemple affiche les éléments dans l’ordre de tri ne respectant 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> est le nombre d’éléments qu’il SortedList<TKey,TValue> peut contenir avant le redimensionnement. À mesure que les éléments sont ajoutés à un SortedList<TKey,TValue>, la capacité est automatiquement augmentée 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 lors de l’ajout SortedList<TKey,TValue>d’éléments au .

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

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

Voir aussi

S’applique à