นี่คือ Dictionary ของเราที่มีสมาชิกบางส่วน:
Dictionary<int, string> d = new Dictionary<int, string>()
{
{1, "Electronics"},
{2, "Clothing"},
{3, "Toys"},
{4, "Footwear"},
{5, "Accessories"}
};
ตอนนี้เพื่อแสดงสมาชิกแรก ให้ตั้งค่าคีย์ (key) ว่า:
d[1];
ข้างต้นจะแสดงสมาชิกแรก
ตัวอย่าง
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Dictionary<int, string> d = new Dictionary<int, string>()
{
{1, "Electronics"},
{2, "Clothing"},
{3, "Toys"},
{4, "Footwear"},
{5, "Accessories"}
};
foreach (KeyValuePair<int, string> ele in d)
{
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
Console.WriteLine("First element: " + d[1]);
}
}
ผลลัพธ์
Key = 1, Value = Electronics
Key = 2, Value = Clothing
Key = 3, Value = Toys
Key = 4, Value = Footwear
Key = 5, Value = Accessories
First element: Electronics