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

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

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

句法:

public virtual object GetByIndex (int index);

这里的index是要获取的值的从零开始的索引。

返回值:返回SortedList对象的指定索引处的值。

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

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

范例1:

// C# code to get the value 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("1", "C++");
        mylist.Add("2", "Java");
        mylist.Add("3", "DSA");
        mylist.Add("4", "Python");
        mylist.Add("5", "C#");
  
        // getting the indexing and
        // store into a variable
        int i = 4;
  
        // getting the value at index 4
        Console.WriteLine("Value at index {0} is {1}",
                          i, mylist.GetByIndex(i));
    }
}

输出:

Value at index 4 is C#

范例2:

// C# code to get the value 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");
  
        // getting the indexing and
        // store into a variable
        // it will give error as
        // index is out of range
        int i = 7;
  
        // getting the value at index 7
        Console.WriteLine("Value at index {0} is {1}",
                          i, mylist.GetByIndex(i));
    }
}

运行时错误:

参考:

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