C# | Obtener la clave en el índice especificado de un objeto SortedList – Part 1

El método SortedList.GetKey(Int32) se usa para obtener la clave en el índice especificado de un objeto SortedList.

Sintaxis:

public virtual object GetKey (int index);

Aquí, index es el índice de base cero de la clave a obtener.

Valor devuelto: este método devuelve la clave en el índice especificado del objeto SortedList.

Excepción: este método se lanza ArgumentOutOfRangeException si el índice está fuera del rango de índices válidos para el objeto SortedList.

Los siguientes programas ilustran el uso del método mencionado anteriormente:

Ejemplo 1:

// C# code to get the key at
// the specified index of a
// SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("key1", "C++");
        mylist.Add("key2", "Java");
        mylist.Add("key3", "DSA");
        mylist.Add("key4", "Python");
        mylist.Add("key5", "C#");
  
        // storing the value of
        // index that needed by
        // used into a variable
        int i = 2;
  
        // getting the key at index 2
        Console.WriteLine("Key at index {0} is {1}",
                          i, mylist.GetKey(i));
    }
}

Producción:

Key at index 2 is key3

Ejemplo 2:

// C# code to get the key at
// the specified index of a
// SortedList object
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a SortedList of integers
        SortedList mylist = new SortedList();
  
        // Adding elements to SortedList
        mylist.Add("First", "Ram");
        mylist.Add("Second", "Shyam");
        mylist.Add("Third", "Mohit");
        mylist.Add("Fourth", "Rohit");
        mylist.Add("Fifth", "Manish");
  
        // storing the value of
        // index that needed by
        // used into a variable
        // it will throw an exception
        // as index is out of range of 
        // valid indexes of SortedList object
        int i = 7;
  
        // getting the key at index 7
        Console.WriteLine("Key at index {0} is {1}",
                          i, mylist.GetKey(i));
    }
}

Error de tiempo de ejecución:

Excepción no controlada:
System.ArgumentOutOfRangeException: el índice estaba fuera de rango. Debe ser no negativo y menor que el tamaño de la colección.
Nombre del parámetro: índice

Referencia:

Publicación traducida automáticamente

Artículo escrito por Kirti_Mangal 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 *