Hashtable.Keys属性用于获取包含Hashtable中的键的ICollection。
句法:
public virtual System.Collections.ICollection Keys { get; }
返回值:该属性返回一个ICollection,其中包含哈希表中的键。
笔记:
- ICollection中的键顺序未指定。
- 检索此属性的值是O(1)操作。
下面的程序说明了上面讨论的属性的用法:
范例1:
// C# code to get an ICollection containing
// the keys in the Hashtable.
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("4", "Even");
myTable.Add("9", "Odd");
myTable.Add("5", "Odd and Prime");
myTable.Add("2", "Even and Prime");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
输出:
5: Odd and Prime
9: Odd
2: Even and Prime
4: Even
范例2:
// C# code to get an ICollection containing
// the keys in the Hashtable.
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Hashtable
Hashtable myTable = new Hashtable();
// Adding elements in Hashtable
myTable.Add("India", "Country");
myTable.Add("Chandigarh", "City");
myTable.Add("Mars", "Planet");
myTable.Add("China", "Country");
// Get a collection of the keys.
ICollection c = myTable.Keys;
// Displaying the contents
foreach(string str in c)
Console.WriteLine(str + ": " + myTable[str]);
}
}
输出:
Chandigarh: City
India: Country
China: Country
Mars: Planet
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.keys?view=netframework-4.7.2