SortedList.Keys属性用于获取SortedList对象中的键。
句法:
public virtual System.Collections.ICollection Keys { get; }
属性值:一个ICollection对象,其中包含SortedList对象中的键。
下面的程序说明了上面讨论的属性的用法:
范例1:
// C# code to get an ICollection containing
// the keys in the SortedList
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a SortedList
SortedList mylist = new SortedList();
// Adding elements in SortedList
mylist.Add("4", "Even");
mylist.Add("9", "Odd");
mylist.Add("5", "Odd and Prime");
mylist.Add("2", "Even and Prime");
// Get a collection of the keys.
ICollection c = mylist.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + mylist[str]);
}
}
输出:
2: Even and Prime
4: Even
5: Odd and Prime
9: Odd
范例2:
// C# code to get an ICollection containing
// the keys in the SortedList.
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a SortedList
SortedList mylist = new SortedList();
// Adding elements in SortedList
mylist.Add("India", "Country");
mylist.Add("Chandigarh", "City");
mylist.Add("Mars", "Planet");
mylist.Add("China", "Country");
// Get a collection of the keys.
ICollection c = mylist.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + mylist[str]);
}
}
输出:
Chandigarh: City
China: Country
India: Country
Mars: Planet
笔记:
- ICollection对象是SortedList对象的键的只读视图。对基础SortedList的修改将立即反映在ICollection中。
- ICollection的元素按与SortedList的键相同的顺序排序。
- 此属性类似于GetKeyList方法,但返回ICollection对象而不是IList对象。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.keys?view=netframework-4.7.2