C# 程序从字典中获取键列表
csharpprogrammingserver side programming更新于 2025/9/17 3:50:00
设置字典元素 −
Dictionary<int, string> d = new Dictionary<int, string>(); // 字典元素 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>();
// 字典元素
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);
Console.WriteLine("显示键...");
foreach (int res in keys) {
Console.WriteLine(res);
}
}
}
输出
显示键... 1 2 3 4 5 6 7 8

