Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C # เพื่อรับรายการคีย์จาก Dictionary


ตั้งค่าองค์ประกอบพจนานุกรม -

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