C# 程序,以获取字典中的键列表
设置字典元素 -
Dictionary<int, string> d = new Dictionary<int, string>(); // dictionary elements d.Add(1, "One"); d.Add(2, "Two"); d.Add(3, "Three"); d.Add(4, "Four"); d.Add(5, "Five"); d.Add(6, "Six"); d.Add(7, "Seven"); d.Add(8, "Eight");
若要获取键,请使用列表集合 -
List<int> keys = new List<int>(d.Keys);
循环遍历键并显示它们。
以下是完整代码 -
示例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Dictionary<int, string> d = new Dictionary<int, string>();
// dictionary elements
d.Add(1, "One");
d.Add(2, "Two");
d.Add(3, "Three");
d.Add(4, "Four");
d.Add(5, "Five");
d.Add(6, "Six");
d.Add(7, "Seven");
d.Add(8, "Eight");
// getting keys
List<int> keys = new List<int>(d.Keys);
Console.WriteLine("Displaying keys...");
foreach (int res in keys) {
Console.WriteLine(res);
}
}
}输出
Displaying keys... 1 2 3 4 5 6 7 8
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP