Compartir vía


SortedList Constructores

Definición

Inicializa una nueva instancia de la clase SortedList.

Sobrecargas

SortedList()

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial predeterminada y está ordenada en función de la interfaz IComparable implementada por cada clave agregada al objeto SortedList.

SortedList(IComparer)

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial predeterminada y está ordenada de acuerdo con la interfaz IComparer especificada.

SortedList(IDictionary)

Inicializa una nueva instancia de la clase SortedList que contiene elementos copiados del diccionario especificado, tiene la misma capacidad inicial que el número de elementos copiados y se ordena de acuerdo con la interfaz IComparable implementada por cada clave.

SortedList(Int32)

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial especificada y está ordenada en función de la interfaz IComparable implementada por cada clave agregada al objeto SortedList.

SortedList(IComparer, Int32)

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial especificada y está ordenada de acuerdo con la interfaz IComparer especificada.

SortedList(IDictionary, IComparer)

Inicializa una nueva instancia de la clase SortedList que contiene elementos copiados del diccionario especificado, tiene la misma capacidad inicial que el número de elementos copiados y se ordena de acuerdo con la interfaz IComparer especificada.

SortedList()

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

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial predeterminada y está ordenada en función de la interfaz IComparable implementada por cada clave agregada al objeto SortedList.

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

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.


// The following code example creates SortedList instances using different constructors
// and demonstrates the differences in the behavior of the SortedList instances.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList;
   Console::WriteLine( "mySL1 (default):" );
   mySL1->Add( "FIRST", "Hello" );
   mySL1->Add( "SECOND", "World" );
   mySL1->Add( "THIRD", "!" );

   try   { mySL1->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( gcnew CaseInsensitiveComparer );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   mySL2->Add( "FIRST", "Hello" );
   mySL2->Add( "SECOND", "World" );
   mySL2->Add( "THIRD", "!" );

   try   { mySL2->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL2 );
   
   // Create a SortedList using the specified KeyComparer.
   // The KeyComparer uses a case-insensitive hash code provider and a case-insensitive comparer,
   // which are based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
   CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
   SortedList^ mySL3 = gcnew SortedList( gcnew CaseInsensitiveComparer( myCul ) );
   Console::WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):" );
   mySL3->Add( "FIRST", "Hello" );
   mySL3->Add( "SECOND", "World" );
   mySL3->Add( "THIRD", "!" );

   try   { mySL3->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL3 );
   
   // Create a SortedList using the ComparisonType.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( StringComparer::InvariantCultureIgnoreCase );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   mySL4->Add( "FIRST", "Hello" );
   mySL4->Add( "SECOND", "World" );
   mySL4->Add( "THIRD", "!" );

   try   { mySL4->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL4 );

    Console::WriteLine("\n\nHit ENTER to return");
    Console::ReadLine();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList();
        Console.WriteLine("mySL1 (default):");
        mySL1.Add("FIRST", "Hello");
        mySL1.Add("SECOND", "World");
        mySL1.Add("THIRD", "!");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(new CaseInsensitiveComparer());
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        mySL2.Add("FIRST", "Hello");
        mySL2.Add("SECOND", "World");
        mySL2.Add("THIRD", "!");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 = new SortedList(new CaseInsensitiveComparer(myCul));
        Console.WriteLine(
            "mySL3 (case-insensitive comparer, Turkish culture):");

        mySL3.Add("FIRST", "Hello");
        mySL3.Add("SECOND", "World");
        mySL3.Add("THIRD", "!");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            StringComparer.InvariantCultureIgnoreCase);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        mySL4.Add("FIRST", "Hello");
        mySL4.Add("SECOND", "World");
        mySL4.Add("THIRD", "!");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList()
        Console.WriteLine("mySL1 (default):")
        mySL1.Add("FIRST", "Hello")
        mySL1.Add("SECOND", "World")
        mySL1.Add("THIRD", "!")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(New CaseInsensitiveComparer())
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        mySL2.Add("FIRST", "Hello")
        mySL2.Add("SECOND", "World")
        mySL2.Add("THIRD", "!")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(New CaseInsensitiveComparer(myCul))
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        mySL3.Add("FIRST", "Hello")
        mySL3.Add("SECOND", "World")
        mySL3.Add("THIRD", "!")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList( _
            StringComparer.InvariantCultureIgnoreCase)

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        mySL4.Add("FIRST", "Hello")
        mySL4.Add("SECOND", "World")
        mySL4.Add("THIRD", "!")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)
    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("     {0,-6}: {1}", _
               myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto . Los elementos se ordenan según la IComparable implementación de cada clave agregada a SortedList.

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(1) operación.

Consulte también

Se aplica a

SortedList(IComparer)

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

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial predeterminada y está ordenada de acuerdo con la interfaz IComparer especificada.

public:
 SortedList(System::Collections::IComparer ^ comparer);
public SortedList (System.Collections.IComparer comparer);
public SortedList (System.Collections.IComparer? comparer);
new System.Collections.SortedList : System.Collections.IComparer -> System.Collections.SortedList
Public Sub New (comparer As IComparer)

Parámetros

comparer
IComparer

Implementación de IComparer que se va a usar al comparar claves.

o bien

null para usar la implementación de IComparable para cada una de las claves.

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.


// The following code example creates SortedList instances using different constructors
// and demonstrates the differences in the behavior of the SortedList instances.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList;
   Console::WriteLine( "mySL1 (default):" );
   mySL1->Add( "FIRST", "Hello" );
   mySL1->Add( "SECOND", "World" );
   mySL1->Add( "THIRD", "!" );

   try   { mySL1->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( gcnew CaseInsensitiveComparer );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   mySL2->Add( "FIRST", "Hello" );
   mySL2->Add( "SECOND", "World" );
   mySL2->Add( "THIRD", "!" );

   try   { mySL2->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL2 );
   
   // Create a SortedList using the specified KeyComparer.
   // The KeyComparer uses a case-insensitive hash code provider and a case-insensitive comparer,
   // which are based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
   CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
   SortedList^ mySL3 = gcnew SortedList( gcnew CaseInsensitiveComparer( myCul ) );
   Console::WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):" );
   mySL3->Add( "FIRST", "Hello" );
   mySL3->Add( "SECOND", "World" );
   mySL3->Add( "THIRD", "!" );

   try   { mySL3->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL3 );
   
   // Create a SortedList using the ComparisonType.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( StringComparer::InvariantCultureIgnoreCase );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   mySL4->Add( "FIRST", "Hello" );
   mySL4->Add( "SECOND", "World" );
   mySL4->Add( "THIRD", "!" );

   try   { mySL4->Add( "first", "Ola!" ); }
   catch ( ArgumentException^ e ) { Console::WriteLine( e ); }

   PrintKeysAndValues( mySL4 );

    Console::WriteLine("\n\nHit ENTER to return");
    Console::ReadLine();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList();
        Console.WriteLine("mySL1 (default):");
        mySL1.Add("FIRST", "Hello");
        mySL1.Add("SECOND", "World");
        mySL1.Add("THIRD", "!");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(new CaseInsensitiveComparer());
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        mySL2.Add("FIRST", "Hello");
        mySL2.Add("SECOND", "World");
        mySL2.Add("THIRD", "!");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 = new SortedList(new CaseInsensitiveComparer(myCul));
        Console.WriteLine(
            "mySL3 (case-insensitive comparer, Turkish culture):");

        mySL3.Add("FIRST", "Hello");
        mySL3.Add("SECOND", "World");
        mySL3.Add("THIRD", "!");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            StringComparer.InvariantCultureIgnoreCase);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        mySL4.Add("FIRST", "Hello");
        mySL4.Add("SECOND", "World");
        mySL4.Add("THIRD", "!");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList()
        Console.WriteLine("mySL1 (default):")
        mySL1.Add("FIRST", "Hello")
        mySL1.Add("SECOND", "World")
        mySL1.Add("THIRD", "!")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(New CaseInsensitiveComparer())
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        mySL2.Add("FIRST", "Hello")
        mySL2.Add("SECOND", "World")
        mySL2.Add("THIRD", "!")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(New CaseInsensitiveComparer(myCul))
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        mySL3.Add("FIRST", "Hello")
        mySL3.Add("SECOND", "World")
        mySL3.Add("THIRD", "!")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList( _
            StringComparer.InvariantCultureIgnoreCase)

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        mySL4.Add("FIRST", "Hello")
        mySL4.Add("SECOND", "World")
        mySL4.Add("THIRD", "!")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)
    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("     {0,-6}: {1}", _
               myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Los elementos se ordenan según la implementación especificada IComparer . Si el comparer parámetro es null, se usa la IComparable implementación de cada clave; por lo tanto, cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto .

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(1) operación.

Consulte también

Se aplica a

SortedList(IDictionary)

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

Inicializa una nueva instancia de la clase SortedList que contiene elementos copiados del diccionario especificado, tiene la misma capacidad inicial que el número de elementos copiados y se ordena de acuerdo con la interfaz IComparable implementada por cada clave.

public:
 SortedList(System::Collections::IDictionary ^ d);
public SortedList (System.Collections.IDictionary d);
new System.Collections.SortedList : System.Collections.IDictionary -> System.Collections.SortedList
Public Sub New (d As IDictionary)

Parámetros

d
IDictionary

Implementación de IDictionary que se va a copiar en un nuevo objeto SortedList.

Excepciones

Uno o más elementos de la d no implementan la interfaz de IComparable.

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.



using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create the dictionary.
   Hashtable^ myHT = gcnew Hashtable;
   myHT->Add( "FIRST", "Hello" );
   myHT->Add( "SECOND", "World" );
   myHT->Add( "THIRD", "!" );
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList( myHT );
   Console::WriteLine( "mySL1 (default):" );
   try
   {
      mySL1->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( myHT,gcnew CaseInsensitiveComparer );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   try
   {
      mySL2->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL2 );
   
    // Create a SortedList using the specified CaseInsensitiveComparer,
    // which is based on the Turkish culture (tr-TR), where "I" is not
    // the uppercase version of "i".
   CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
   SortedList^ mySL3 = gcnew SortedList( myHT, gcnew CaseInsensitiveComparer( myCul ) );
   Console::WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):" );
   try
   {
      mySL3->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL3 );
   
   // Create a SortedList using the ComparisonType.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( myHT, StringComparer::InvariantCultureIgnoreCase );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   try
   {
      mySL4->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL4 );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create the dictionary.
        Hashtable myHT = new Hashtable();
        myHT.Add("FIRST", "Hello");
        myHT.Add("SECOND", "World");
        myHT.Add("THIRD", "!");

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList(myHT);
        Console.WriteLine("mySL1 (default):");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(myHT, new CaseInsensitiveComparer());
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 = new SortedList(myHT, new CaseInsensitiveComparer(myCul));
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            myHT, StringComparer.InvariantCultureIgnoreCase);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create the dictionary.
        Dim myHT As New Hashtable()
        myHT.Add("FIRST", "Hello")
        myHT.Add("SECOND", "World")
        myHT.Add("THIRD", "!")

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList(myHT)
        Console.WriteLine("mySL1 (default):")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(myHT, New CaseInsensitiveComparer())
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(myHT, New CaseInsensitiveComparer(myCul))
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the 
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList(myHT, StringComparer.InvariantCultureIgnoreCase)
        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)

    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("        {0,-6}: {1}", _
                myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto . Los elementos se ordenan según la IComparable implementación de cada clave agregada a SortedList.

Un Hashtable objeto es un ejemplo de una IDictionary implementación que se puede pasar a este constructor. El nuevo SortedList objeto contiene una copia de las claves y los valores almacenados en .Hashtable

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(n) operación, donde n es el número de elementos de d.

Consulte también

Se aplica a

SortedList(Int32)

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

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial especificada y está ordenada en función de la interfaz IComparable implementada por cada clave agregada al objeto SortedList.

public:
 SortedList(int initialCapacity);
public SortedList (int initialCapacity);
new System.Collections.SortedList : int -> System.Collections.SortedList
Public Sub New (initialCapacity As Integer)

Parámetros

initialCapacity
Int32

Número inicial de elementos que puede contener el objeto SortedList.

Excepciones

initialCapacity es menor que cero.

No hay suficiente memoria disponible para crear un objeto SortedList con el parámetro initialCapacity especificado.

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.

// The following code example creates SortedList instances using different constructors
// and demonstrates the differences in the behavior of the SortedList instances.



using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        Capacity is {0}.", myList->Capacity );
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList( 3 );
   Console::WriteLine( "mySL1 (default):" );
   mySL1->Add( "FIRST", "Hello" );
   mySL1->Add( "SECOND", "World" );
   mySL1->Add( "THIRD", "!" );
   try
   {
      mySL1->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( gcnew CaseInsensitiveComparer,3 );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   mySL2->Add( "FIRST", "Hello" );
   mySL2->Add( "SECOND", "World" );
   mySL2->Add( "THIRD", "!" );
   try
   {
      mySL2->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL2 );
   
    // Create a SortedList using the specified CaseInsensitiveComparer,
    // which is based on the Turkish culture (tr-TR), where "I" is not
    // the uppercase version of "i".
    CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
    SortedList^ mySL3 = gcnew SortedList(gcnew CaseInsensitiveComparer(myCul), 3);

    Console::WriteLine("mySL3 (case-insensitive comparer, Turkish culture):");

    mySL3->Add("FIRST", "Hello");
    mySL3->Add("SECOND", "World");
    mySL3->Add("THIRD", "!");
    try
    {
        mySL3->Add("first", "Ola!");
    }
    catch (ArgumentException^ e)
    {
        Console::WriteLine(e);
    }
    PrintKeysAndValues(mySL3);

    // Create a SortedList using the
    // StringComparer.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( StringComparer::InvariantCultureIgnoreCase, 3 );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   mySL4->Add( "FIRST", "Hello" );
   mySL4->Add( "SECOND", "World" );
   mySL4->Add( "THIRD", "!" );
   try
   {
      mySL4->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL4 );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        Capacity is 6.
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        Capacity is 3.
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        Capacity is 6.
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        Capacity is 3.
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList( 3 );
        Console.WriteLine("mySL1 (default):");
        mySL1.Add("FIRST", "Hello");
        mySL1.Add("SECOND", "World");
        mySL1.Add("THIRD", "!");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(new CaseInsensitiveComparer(), 3);
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        mySL2.Add("FIRST", "Hello");
        mySL2.Add("SECOND", "World");
        mySL2.Add("THIRD", "!");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 =
            new SortedList(new CaseInsensitiveComparer(myCul), 3);

        Console.WriteLine(
            "mySL3 (case-insensitive comparer, Turkish culture):");

        mySL3.Add("FIRST", "Hello");
        mySL3.Add("SECOND", "World");
        mySL3.Add("THIRD", "!");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            StringComparer.InvariantCultureIgnoreCase, 3);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        mySL4.Add("FIRST", "Hello");
        mySL4.Add("SECOND", "World");
        mySL4.Add("THIRD", "!");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList( 3 )
        Console.WriteLine("mySL1 (default):")
        mySL1.Add("FIRST", "Hello")
        mySL1.Add("SECOND", "World")
        mySL1.Add("THIRD", "!")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(New CaseInsensitiveComparer(), 3)
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        mySL2.Add("FIRST", "Hello")
        mySL2.Add("SECOND", "World")
        mySL2.Add("THIRD", "!")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(New CaseInsensitiveComparer(myCul), 3)
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        mySL3.Add("FIRST", "Hello")
        mySL3.Add("SECOND", "World")
        mySL3.Add("THIRD", "!")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList( _
            StringComparer.InvariantCultureIgnoreCase, 3)

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        mySL4.Add("FIRST", "Hello")
        mySL4.Add("SECOND", "World")
        mySL4.Add("THIRD", "!")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)
    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("     {0,-6}: {1}", _
               myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto . Los elementos se ordenan según la IComparable implementación de cada clave agregada a SortedList.

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(n) operación, donde n es initialCapacity.

Consulte también

Se aplica a

SortedList(IComparer, Int32)

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

Inicializa una nueva instancia de la clase SortedList que está vacía, tiene la capacidad inicial especificada y está ordenada de acuerdo con la interfaz IComparer especificada.

public:
 SortedList(System::Collections::IComparer ^ comparer, int capacity);
public SortedList (System.Collections.IComparer comparer, int capacity);
public SortedList (System.Collections.IComparer? comparer, int capacity);
new System.Collections.SortedList : System.Collections.IComparer * int -> System.Collections.SortedList
Public Sub New (comparer As IComparer, capacity As Integer)

Parámetros

comparer
IComparer

Implementación de IComparer que se va a usar al comparar claves.

o bien

null para usar la implementación de IComparable para cada una de las claves.

capacity
Int32

Número inicial de elementos que puede contener el objeto SortedList.

Excepciones

capacity es menor que cero.

No hay suficiente memoria disponible para crear un objeto SortedList con el parámetro capacity especificado.

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.

// The following code example creates SortedList instances using different constructors
// and demonstrates the differences in the behavior of the SortedList instances.



using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        Capacity is {0}.", myList->Capacity );
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList( 3 );
   Console::WriteLine( "mySL1 (default):" );
   mySL1->Add( "FIRST", "Hello" );
   mySL1->Add( "SECOND", "World" );
   mySL1->Add( "THIRD", "!" );
   try
   {
      mySL1->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( gcnew CaseInsensitiveComparer,3 );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   mySL2->Add( "FIRST", "Hello" );
   mySL2->Add( "SECOND", "World" );
   mySL2->Add( "THIRD", "!" );
   try
   {
      mySL2->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL2 );
   
    // Create a SortedList using the specified CaseInsensitiveComparer,
    // which is based on the Turkish culture (tr-TR), where "I" is not
    // the uppercase version of "i".
    CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
    SortedList^ mySL3 = gcnew SortedList(gcnew CaseInsensitiveComparer(myCul), 3);

    Console::WriteLine("mySL3 (case-insensitive comparer, Turkish culture):");

    mySL3->Add("FIRST", "Hello");
    mySL3->Add("SECOND", "World");
    mySL3->Add("THIRD", "!");
    try
    {
        mySL3->Add("first", "Ola!");
    }
    catch (ArgumentException^ e)
    {
        Console::WriteLine(e);
    }
    PrintKeysAndValues(mySL3);

    // Create a SortedList using the
    // StringComparer.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( StringComparer::InvariantCultureIgnoreCase, 3 );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   mySL4->Add( "FIRST", "Hello" );
   mySL4->Add( "SECOND", "World" );
   mySL4->Add( "THIRD", "!" );
   try
   {
      mySL4->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL4 );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        Capacity is 6.
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        Capacity is 3.
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        Capacity is 6.
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        Capacity is 3.
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList( 3 );
        Console.WriteLine("mySL1 (default):");
        mySL1.Add("FIRST", "Hello");
        mySL1.Add("SECOND", "World");
        mySL1.Add("THIRD", "!");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(new CaseInsensitiveComparer(), 3);
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        mySL2.Add("FIRST", "Hello");
        mySL2.Add("SECOND", "World");
        mySL2.Add("THIRD", "!");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 =
            new SortedList(new CaseInsensitiveComparer(myCul), 3);

        Console.WriteLine(
            "mySL3 (case-insensitive comparer, Turkish culture):");

        mySL3.Add("FIRST", "Hello");
        mySL3.Add("SECOND", "World");
        mySL3.Add("THIRD", "!");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            StringComparer.InvariantCultureIgnoreCase, 3);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        mySL4.Add("FIRST", "Hello");
        mySL4.Add("SECOND", "World");
        mySL4.Add("THIRD", "!");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList( 3 )
        Console.WriteLine("mySL1 (default):")
        mySL1.Add("FIRST", "Hello")
        mySL1.Add("SECOND", "World")
        mySL1.Add("THIRD", "!")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(New CaseInsensitiveComparer(), 3)
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        mySL2.Add("FIRST", "Hello")
        mySL2.Add("SECOND", "World")
        mySL2.Add("THIRD", "!")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(New CaseInsensitiveComparer(myCul), 3)
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        mySL3.Add("FIRST", "Hello")
        mySL3.Add("SECOND", "World")
        mySL3.Add("THIRD", "!")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList( _
            StringComparer.InvariantCultureIgnoreCase, 3)

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        mySL4.Add("FIRST", "Hello")
        mySL4.Add("SECOND", "World")
        mySL4.Add("THIRD", "!")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)
    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("     {0,-6}: {1}", _
               myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Los elementos se ordenan según la implementación especificada IComparer . Si el comparer parámetro es null, se usa la IComparable implementación de cada clave; por lo tanto, cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto .

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(n) operación, donde n es capacity.

Consulte también

Se aplica a

SortedList(IDictionary, IComparer)

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

Inicializa una nueva instancia de la clase SortedList que contiene elementos copiados del diccionario especificado, tiene la misma capacidad inicial que el número de elementos copiados y se ordena de acuerdo con la interfaz IComparer especificada.

public:
 SortedList(System::Collections::IDictionary ^ d, System::Collections::IComparer ^ comparer);
public SortedList (System.Collections.IDictionary d, System.Collections.IComparer comparer);
public SortedList (System.Collections.IDictionary d, System.Collections.IComparer? comparer);
new System.Collections.SortedList : System.Collections.IDictionary * System.Collections.IComparer -> System.Collections.SortedList
Public Sub New (d As IDictionary, comparer As IComparer)

Parámetros

d
IDictionary

Implementación de IDictionary que se va a copiar en un nuevo objeto SortedList.

comparer
IComparer

Implementación de IComparer que se va a usar al comparar claves.

o bien

null para usar la implementación de IComparable para cada una de las claves.

Excepciones

comparer es null y uno o más elementos de la d no implementan la interfaz de IComparable.

Ejemplos

En el ejemplo de código siguiente se crean colecciones con distintos SortedList constructores y se muestran las diferencias en el comportamiento de las colecciones.



using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
void PrintKeysAndValues( SortedList^ myList )
{
   Console::WriteLine( "        -KEY-   -VALUE-" );
   for ( int i = 0; i < myList->Count; i++ )
   {
      Console::WriteLine( "        {0,-6}: {1}", myList->GetKey( i ), myList->GetByIndex( i ) );

   }
   Console::WriteLine();
}

int main()
{
   
   // Create the dictionary.
   Hashtable^ myHT = gcnew Hashtable;
   myHT->Add( "FIRST", "Hello" );
   myHT->Add( "SECOND", "World" );
   myHT->Add( "THIRD", "!" );
   
   // Create a SortedList using the default comparer.
   SortedList^ mySL1 = gcnew SortedList( myHT );
   Console::WriteLine( "mySL1 (default):" );
   try
   {
      mySL1->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL1 );
   
   // Create a SortedList using the specified case-insensitive comparer.
   SortedList^ mySL2 = gcnew SortedList( myHT,gcnew CaseInsensitiveComparer );
   Console::WriteLine( "mySL2 (case-insensitive comparer):" );
   try
   {
      mySL2->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL2 );
   
    // Create a SortedList using the specified CaseInsensitiveComparer,
    // which is based on the Turkish culture (tr-TR), where "I" is not
    // the uppercase version of "i".
   CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
   SortedList^ mySL3 = gcnew SortedList( myHT, gcnew CaseInsensitiveComparer( myCul ) );
   Console::WriteLine( "mySL3 (case-insensitive comparer, Turkish culture):" );
   try
   {
      mySL3->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL3 );
   
   // Create a SortedList using the ComparisonType.InvariantCultureIgnoreCase value.
   SortedList^ mySL4 = gcnew SortedList( myHT, StringComparer::InvariantCultureIgnoreCase );
   Console::WriteLine( "mySL4 (InvariantCultureIgnoreCase):" );
   try
   {
      mySL4->Add( "first", "Ola!" );
   }
   catch ( ArgumentException^ e ) 
   {
      Console::WriteLine( e );
   }

   PrintKeysAndValues( mySL4 );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
using System;
using System.Collections;
using System.Globalization;

public class SamplesSortedList
{

    public static void Main()
    {

        // Create the dictionary.
        Hashtable myHT = new Hashtable();
        myHT.Add("FIRST", "Hello");
        myHT.Add("SECOND", "World");
        myHT.Add("THIRD", "!");

        // Create a SortedList using the default comparer.
        SortedList mySL1 = new SortedList(myHT);
        Console.WriteLine("mySL1 (default):");
        try
        {
            mySL1.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL1);

        // Create a SortedList using the specified case-insensitive comparer.
        SortedList mySL2 = new SortedList(myHT, new CaseInsensitiveComparer());
        Console.WriteLine("mySL2 (case-insensitive comparer):");
        try
        {
            mySL2.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL2);

        // Create a SortedList using the specified CaseInsensitiveComparer,
        // which is based on the Turkish culture (tr-TR), where "I" is not
        // the uppercase version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        SortedList mySL3 = new SortedList(myHT, new CaseInsensitiveComparer(myCul));
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):");
        try
        {
            mySL3.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL3);

        // Create a SortedList using the
        // StringComparer.InvariantCultureIgnoreCase value.
        SortedList mySL4 = new SortedList(
            myHT, StringComparer.InvariantCultureIgnoreCase);

        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):");
        try
        {
            mySL4.Add("first", "Ola!");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e);
        }
        PrintKeysAndValues(mySL4);
    }

    public static void PrintKeysAndValues(SortedList myList)
    {
        Console.WriteLine("        -KEY-   -VALUE-");
        for (int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine("        {0,-6}: {1}",
                myList.GetKey(i), myList.GetByIndex(i));
        }
        Console.WriteLine();
    }
}


/*
This code produces the following output.  Results vary depending on the system's culture settings.

mySL1 (default):
        -KEY-   -VALUE-
        first : Ola!
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL2 (case-insensitive comparer):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

mySL3 (case-insensitive comparer, Turkish culture):
        -KEY-   -VALUE-
        FIRST : Hello
        first : Ola!
        SECOND: World
        THIRD : !

mySL4 (InvariantCultureIgnoreCase):
System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first'
   at System.Collections.SortedList.Add(Object key, Object value)
   at SamplesSortedList.Main()
        -KEY-   -VALUE-
        FIRST : Hello
        SECOND: World
        THIRD : !

*/
Imports System.Collections
Imports System.Globalization

Public Class SamplesSortedList

    Public Shared Sub Main()

        ' Create the dictionary.
        Dim myHT As New Hashtable()
        myHT.Add("FIRST", "Hello")
        myHT.Add("SECOND", "World")
        myHT.Add("THIRD", "!")

        ' Create a SortedList using the default comparer.
        Dim mySL1 As New SortedList(myHT)
        Console.WriteLine("mySL1 (default):")
        Try
            mySL1.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL1)

        ' Create a SortedList using the specified case-insensitive comparer.
        Dim mySL2 As New SortedList(myHT, New CaseInsensitiveComparer())
        Console.WriteLine("mySL2 (case-insensitive comparer):")
        Try
            mySL2.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL2)

        ' Create a SortedList using the specified CaseInsensitiveComparer,
        ' which is based on the Turkish culture (tr-TR), where "I" is not
        ' the uppercase version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim mySL3 As New SortedList(myHT, New CaseInsensitiveComparer(myCul))
        Console.WriteLine("mySL3 (case-insensitive comparer, Turkish culture):")
        Try
            mySL3.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL3)

        ' Create a SortedList using the 
        ' StringComparer.InvariantCultureIgnoreCase value.
        Dim mySL4 As New SortedList(myHT, StringComparer.InvariantCultureIgnoreCase)
        Console.WriteLine("mySL4 (InvariantCultureIgnoreCase):")
        Try
            mySL4.Add("first", "Ola!")
        Catch e As ArgumentException
            Console.WriteLine(e)
        End Try
        PrintKeysAndValues(mySL4)

    End Sub

    Public Shared Sub PrintKeysAndValues(ByVal myList As SortedList)
        Console.WriteLine("        -KEY-   -VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("        {0,-6}: {1}", _
                myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.  Results vary depending on the system's culture settings.
'
'mySL1 (default):
'        -KEY-   -VALUE-
'        first : Ola!
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL2 (case-insensitive comparer):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !
'
'mySL3 (case-insensitive comparer, Turkish culture):
'        -KEY-   -VALUE-
'        FIRST : Hello
'        first : Ola!
'        SECOND: World
'        THIRD : !
'
'mySL4 (InvariantCultureIgnoreCase):
'System.ArgumentException: Item has already been added.  Key in dictionary: 'FIRST'  Key being added: 'first''   at System.Collections.SortedList.Add(Object key, Object value)
'   at SamplesSortedList.Main()
'        -KEY-   -VALUE-
'        FIRST : Hello
'        SECOND: World
'        THIRD : !

Comentarios

Los elementos se ordenan según la implementación especificada IComparer . Si el comparer parámetro es null, se usa la IComparable implementación de cada clave; por lo tanto, cada clave debe implementar la IComparable interfaz para poder realizar comparaciones con cada otra clave del SortedList objeto .

Un Hashtable objeto es un ejemplo de una IDictionary implementación que se puede pasar a este constructor. El nuevo SortedList objeto contiene una copia de las claves y los valores almacenados en .Hashtable

La capacidad de un SortedList objeto es el número de elementos que SortedList puede contener. A medida que se agregan elementos a , SortedListla capacidad aumenta automáticamente según sea necesario mediante la reasignación de la matriz interna.

Si se puede estimar el tamaño de la colección, si se especifica la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al SortedList objeto .

Este constructor es una O(n) operación, donde n es el número de elementos de d.

Consulte también

Se aplica a