SortedList.Add(Object, Object) Método

Definición

Agrega un elemento con la clave y el valor especificados a un SortedList objeto .

public:
 virtual void Add(System::Object ^ key, System::Object ^ value);
public virtual void Add(object key, object value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Overridable Sub Add (key As Object, value As Object)

Parámetros

key
Object

Clave del elemento que se va a agregar.

value
Object

Valor del elemento que se va a agregar. El valor puede ser null.

Implementaciones

Excepciones

key es null.

Ya existe un elemento con el especificado key en el SortedList objeto .

O bien

SortedList se establece para usar la IComparable interfaz y key no implementa la IComparable interfaz .

es SortedList de solo lectura.

O bien

SortedList tiene un tamaño fijo.

No hay suficiente memoria disponible para agregar el elemento a SortedList.

El comparador produce una excepción.

Ejemplos

En el ejemplo de código siguiente se muestra cómo agregar elementos a un SortedList objeto .

using System;
using System.Collections;
public class SamplesSortedList  {

   public static void Main()  {

      // Creates and initializes a new SortedList.
      SortedList mySL = new SortedList();
      mySL.Add( "one", "The" );
      mySL.Add( "two", "quick" );
      mySL.Add( "three", "brown" );
      mySL.Add( "four", "fox" );

      // Displays the SortedList.
      Console.WriteLine( "The SortedList contains the following:" );
      PrintKeysAndValues( mySL );
   }

   public static void PrintKeysAndValues( SortedList myList )  {
      Console.WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
      }
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The SortedList contains the following:
    -KEY-    -VALUE-
    four:    fox
    one:    The
    three:    brown
    two:    quick
*/
Imports System.Collections

Public Class SamplesSortedList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new SortedList.
        Dim mySL As New SortedList()
        mySL.Add("one", "The")
        mySL.Add("two", "quick")
        mySL.Add("three", "brown")
        mySL.Add("four", "fox")
        
        ' Displays the SortedList.
        Console.WriteLine("The SortedList contains the following:")
        PrintKeysAndValues(mySL)
    End Sub    
    
    Public Shared Sub PrintKeysAndValues(myList As SortedList)
        Console.WriteLine(ControlChars.Tab & "-KEY-" & ControlChars.Tab & _
           "-VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine(ControlChars.Tab & "{0}:" & ControlChars.Tab & _
               "{1}", myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' The SortedList contains the following:
'     -KEY-    -VALUE-
'     four:    fox
'     one:    The
'     three:    brown
'     two:    quick

Comentarios

El punto de inserción se determina en función del comparador seleccionado, ya sea explícita o de forma predeterminada, cuando se creó el SortedList objeto.

Si Count ya es Capacityigual a , la capacidad del SortedList objeto aumenta mediante la reasignación automática de la matriz interna y los elementos existentes se copian en la nueva matriz antes de agregar el nuevo elemento.

También puede usar la Item[] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe en el SortedList objeto (por ejemplo, myCollection["myNonexistentKey"] = myValue). Sin embargo, si la clave especificada ya existe en , SortedListal establecer la Item[] propiedad se sobrescribe el valor anterior. En cambio, el Add método no modifica los elementos existentes.

Los elementos de un SortedList objeto se ordenan por las claves según una implementación específica IComparer especificada cuando SortedList se crea o según la IComparable implementación proporcionada por las claves.

Una clave no puede ser null, pero un valor puede ser .

Este método es una O(n) operación para datos no ordenados, donde n es Count. Es una O(log n) operación si el nuevo elemento se agrega al final de la lista. Si la inserción provoca un cambio de tamaño, la operación es O(n).

Se aplica a

Consulte también