📜  C#|在SortedList对象的指定索引处获取键

📅  最后修改于: 2021-05-30 00:30:28             🧑  作者: Mango

SortedList.GetKey(Int32)方法用于在SortedList对象的指定索引处获取键。

句法:

public virtual object GetKey (int index);

在这里, index是要获取的键的从零开始的索引。

返回值:该方法在SortedList对象的指定索引处返回键。

异常:如果索引超出SortedList对象的有效索引范围,则此方法将引发ArgumentOutOfRangeException

下面的程序说明了上面讨论的方法的使用:

范例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));
    }
}

输出:

Key at index 2 is key3

范例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));
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.getkey?view=netframework-4.7.2