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

更新於: 22-Jun-2020

5 千+ 瀏覽

職業生涯起航

透過完成課程獲得認證

開始
廣告