Lista ordenada de C# con ejemplos

En C#, SortedList es una colección de pares clave/valor que se ordenan según las claves. De forma predeterminada, esta colección ordena los pares clave/valor en orden ascendente. Es de tipo genérico y no genérico de colección. La SortedList genérica se define en el espacio de nombres System.Collections.Generic, mientras que la SortedList no genérica se define en el espacio de nombres System.Collections. Aquí analizaremos el tipo SortedList no genérico. 
Puntos importantes: 
 

  • La clase SortedList implementa las interfaces IEnumerable , ICollection , IDictionary e ICloneable .
  • En SortedList, se puede acceder a un elemento por su clave o por su índice.
  • Un objeto SortedList mantiene internamente dos arrays para almacenar los elementos de la lista, es decir, una array para las claves y otra array para los valores asociados.
  • Aquí, una clave no puede ser nula, pero un valor sí puede serlo.
  • La capacidad de un objeto SortedList es el número de pares clave/valor que puede contener.
  • En SortedList, no se permiten claves duplicadas.
  • En SortedList, puede almacenar valores del mismo tipo y de diferentes tipos debido a la colección no genérica. Si usa una lista ordenada genérica en su programa, entonces es necesario que el tipo de valores sea el mismo.
  • En SortedList no puede almacenar claves de diferentes tipos de datos en el mismo SortedList porque el compilador generará una excepción. Por lo tanto, siempre agregue la clave en su SortedList del mismo tipo.
  • También puede convertir el par clave/valor de SortedList en DictionaryEntry.

¿Cómo crear una lista ordenada?

La clase SortedList proporciona 6 tipos diferentes de constructores que se usan para crear una SortedList, aquí solo usamos SortedList(), constructor. Para leer más sobre los constructores de SortedList, puede consultar C# | Clase de lista ordenada .
SortedList(): se utiliza para crear una instancia de la clase SortedList que está vacía, tiene la capacidad inicial predeterminada y se ordena de acuerdo con la interfaz IComparable implementada por cada clave agregada al objeto SortedList. 
Paso 1: incluya el espacio de nombres System.Collections en su programa con la ayuda de la palabra clave:
 

using System.Collections;

Paso 2: Cree una SortedList usando la clase SortedList como se muestra a continuación:
 

SortedList list_name = new SortedList();

Paso 3: si desea agregar un par clave/valor en su SortedList, use el método Add() para agregar pares clave/valor en su SortedList. Y también puede almacenar un par clave/valor en su SortedList sin usar el método Add(), este tipo de sintaxis se conoce como sintaxis de inicialización de colección, como se muestra en el siguiente ejemplo.
Paso 4: Se accede a los pares clave/valor de SortedList de tres maneras diferentes:
 

  • for loop: puede usar for loop para acceder a los pares clave/valor de SortedList.
    Ejemplo:
     

CSharp

for (int x = 0; x < my_slist1.Count; x++)
{
    Console.WriteLine("{0} and {1}",
                my_slist1.GetKey(x),
           my_slist1.GetByIndex(x));
}
  • Usando el índice: puede acceder al valor individual de SortedList usando el índice. Debe pasar la clave o el índice como parámetro para encontrar el valor respectivo. Si la clave especificada no está disponible, el compilador arrojará un error.
    Ejemplo:
     

CSharp

Console.WriteLine("Value is:{0}", my_slist1[1.04]);
 
string x = (string)my_slist[1.02];
 
Console.WriteLine(x);
  • bucle foreach: puede usar un bucle foreach para acceder a los pares clave/valor de SortedList.
    Ejemplo:
     

CSharp

foreach(DictionaryEntry pair in my_slist1)
{
    Console.WriteLine("{0} and {1}",
              pair.Key, pair.Value);
}

Ejemplo:
 

CSharp

// C# program to illustrate how
// to create a sortedlist
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating a sortedlist
        // Using SortedList class
        SortedList my_slist1 = new SortedList();
 
        // Adding key/value pairs in
        // SortedList using Add() method
        my_slist1.Add(1.02, "This");
        my_slist1.Add(1.07, "Is");
        my_slist1.Add(1.04, "SortedList");
        my_slist1.Add(1.01, "Tutorial");
 
        foreach(DictionaryEntry pair in my_slist1)
        {
            Console.WriteLine("{0} and {1}",
                      pair.Key, pair.Value);
        }
        Console.WriteLine();
 
        // Creating another SortedList
        // using Object Initializer Syntax
        // to initialize sortedlist
        SortedList my_slist2 = new SortedList() {
                                  { "b.09", 234 },
                                  { "b.11", 395 },
                                  { "b.01", 405 },
                                  { "b.67", 100 }};
                 
        foreach(DictionaryEntry pair in my_slist2)
        {
            Console.WriteLine("{0} and {1}",
                      pair.Key, pair.Value);
        }
    }
}
Producción: 

1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

b.01 and 405
b.09 and 234
b.11 and 395
b.67 and 100

 

¿Cómo eliminar elementos de SortedList?

  • Borrar : este método se usa para eliminar todos los elementos de un objeto SortedList.
  • Eliminar : este método se utiliza para eliminar el elemento con la clave especificada de un objeto SortedList.
  • RemoveAt : este método se usa para eliminar el elemento en el índice especificado de un objeto SortedList.

Ejemplo:
 

CSharp

// C# program to illustrate how to
// remove key/value pairs from
// the sortedlist
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating a sortedlist
        // Using SortedList class
        SortedList my_slist = new SortedList();
 
        // Adding key/value pairs in SortedList
        // Using Add() method
        my_slist.Add(1.02, "This");
        my_slist.Add(1.07, "Is");
        my_slist.Add(1.04, "SortedList");
        my_slist.Add(1.01, "Tutorial");
 
        foreach(DictionaryEntry pair in my_slist)
        {
            Console.WriteLine("{0} and {1}",
                      pair.Key, pair.Value);
        }
        Console.WriteLine();
 
        // Remove value having 1.07 key
        // Using Remove() method
        my_slist.Remove(1.07);
 
        // After Remove() method
        foreach(DictionaryEntry pair in my_slist)
        {
            Console.WriteLine("{0} and {1}",
                      pair.Key, pair.Value);
        }
        Console.WriteLine();
 
        // Remove element at index 2
        // Using RemoveAt() method
        my_slist.RemoveAt(2);
 
        // After RemoveAt() method
        foreach(DictionaryEntry pair in my_slist)
        {
            Console.WriteLine("{0} and {1}",
                      pair.Key, pair.Value);
        }
        Console.WriteLine();
 
        // Remove all key/value pairs
        // Using Clear method
        my_slist.Clear();
        Console.WriteLine("The total number of key/value pairs"+
                    " present in my_slist:{0}", my_slist.Count);
    }
}
Producción: 

1.01 and Tutorial
1.02 and This
1.04 and SortedList
1.07 and Is

1.01 and Tutorial
1.02 and This
1.04 and SortedList

1.01 and Tutorial
1.02 and This

The total number of key/value pairs present in my_slist:0

 

¿Cómo verificar la disponibilidad del par clave/valor en SortedList?

En SortedList, puede verificar si el par dado está presente o no usando los siguientes métodos:
 

  • Contiene : este método se utiliza para verificar si un objeto SortedList contiene una clave específica.
  • Contiene clave : este método se utiliza para verificar si un objeto SortedList contiene una clave específica.
  • Contiene valor : este método se utiliza para verificar si un objeto SortedList contiene un valor específico.

Ejemplo:
 

CSharp

// C# program to illustrate how to
// check the given key or value
// present in the sortedlist or not
using System;
using System.Collections;
 
class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Creating a sortedlist
        // Using SortedList class
        SortedList my_slist = new SortedList();
 
        // Adding key/value pairs in
        // SortedList using Add() method
        my_slist.Add(1.02, "This");
        my_slist.Add(1.07, "Is");
        my_slist.Add(1.04, "SortedList");
        my_slist.Add(1.01, "Tutorial");
 
        // Using Contains() method to check
        // the specified key is present or not
        if (my_slist.Contains(1.02) == true)
        {
            Console.WriteLine("Key is found...!!");
        }
 
        else
        {
            Console.WriteLine("Key is not found...!!");
        }
 
        // Using ContainsKey() method to check
        // the specified key is present or not
        if (my_slist.ContainsKey(1.03) == true)
        {
            Console.WriteLine("Key is found...!!");
        }
        else
        {
            Console.WriteLine("Key is not found...!!");
        }
 
        // Using ContainsValue() method to check
        // the specified value is present or not
        if (my_slist.ContainsValue("Is") == true)
        {
            Console.WriteLine("Value is found...!!");
        }
 
        else
        {
            Console.WriteLine("Value is not found...!!");
        }
    }
}
Producción: 

Key is found...!!
Key is not found...!!
Value is found...!!

 

Publicación traducida automáticamente

Artículo escrito por ankita_saini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *