SortedList.GetKeyList方法用于获取SortedList对象中的键列表。
句法:
public virtual System.Collections.IList GetKeyList ();
返回值:返回一个IList对象,其中包含SortedList对象中的键。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code for getting the keys
// in 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#");
// taking an IList and
// using GetKeyList method
IList klist = mylist.GetKeyList();
// Prints the list of keys
Console.WriteLine("Key List");
for (int i = 0; i < mylist.Count; i++)
Console.WriteLine(klist[i]);
}
}
输出:
Key List
1
2
3
4
5
范例2:
// C# code for getting the keys
// in 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");
// taking an IList and
// using GetKeyList method
IList klist = mylist.GetKeyList();
// Prints the list of keys
Console.WriteLine("Key List");
// will print the keys in sorted order
for (int i = 0; i < mylist.Count; i++)
Console.WriteLine(klist[i]);
}
}
输出:
Key List
Fifth
First
Fourth
Second
Third
笔记:
- 返回的IList对象是SortedList对象的键的只读视图。对基础SortedList的修改将立即反映在IList中。
- 返回的IList的元素按与SortedList的键相同的顺序排序。
- 此方法类似于Keys属性,但返回一个IList对象,而不是ICollection对象。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.getkeylist?view=netframework-4.7.2