StringDictionary.Keys属性用于获取StringDictionary中的键的集合。
句法:
public virtual System.Collections.ICollection Keys { get; }
返回值:一个ICollection,它提供StringDictionary中的键。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to get a collection
// of keys in the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a StringDictionary named myDict
StringDictionary myDict = new StringDictionary();
// Adding key and value into the StringDictionary
myDict.Add("A", "Apple");
myDict.Add("B", "Banana");
myDict.Add("C", "Cat");
myDict.Add("D", "Dog");
// To copy the StringDictionary values to
// a one-dimensional Array instance at
// the specified index.
String[] myKeys = new String[myDict.Count];
myDict.Keys.CopyTo(myKeys, 0);
// Getting a collection of keys
// in the StringDictionary
for (int i = 0; i < myDict.Count; i++) {
Console.WriteLine(myKeys[i] + " " + myDict[myKeys[i]]);
}
}
}
输出:
d Dog
b Banana
c Cat
a Apple
范例2:
// C# code to get a collection
// of keys in the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a StringDictionary named myDict
StringDictionary myDict = new StringDictionary();
// Adding key and value into the StringDictionary
myDict.Add("3", "prime & odd");
myDict.Add("2", "prime & even");
myDict.Add("4", "non-prime & even");
myDict.Add("9", "non-prime & odd");
// To copy the StringDictionary values to
// a one-dimensional Array instance at
// the specified index.
String[] myKeys = new String[myDict.Count];
myDict.Keys.CopyTo(myKeys, 0);
// Getting a collection of keys
// in the StringDictionary
for (int i = 0; i < myDict.Count; i++) {
Console.WriteLine(myKeys[i] + " " + myDict[myKeys[i]]);
}
}
}
输出:
2 prime & even
3 prime & odd
9 non-prime & odd
4 non-prime & even
笔记:
- ICollection中的键顺序未指定,但与Values方法返回的ICollection中的关联值的顺序相同。
- 返回的ICollection不是静态副本。而是,ICollection引用了原始StringDictionary中的键。因此,对StringDictionary的更改将继续反映在ICollection中。
- 检索此属性的值是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringdictionary.keys?view=netframework-4.7.2