ขั้นแรก ตั้งค่าคอลเลกชันพจนานุกรมที่มีองค์ประกอบ
Dictionary<int, string> d = new Dictionary<int, string>() {
{1,"Applianes"},
{2, "Clothing"},
{3,"Toys"},
{4,"Footwear"},
{5, "Accessories"}
}; สมมติว่าคุณต้องตรวจสอบว่ามีคีย์ 5 อยู่หรือไม่ สำหรับสิ่งนั้น ให้ใช้เมธอด ContainKey() คืนค่า True หากพบคีย์
d.ContainsKey(5);
ให้เราดูรหัสที่สมบูรณ์
ตัวอย่าง
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("Key 5 exists? "+d.ContainsKey(5));
}
} ผลลัพธ์
Key = 1, Value = Electronics Key = 2, Value = Clothing Key = 3, Value = Toys Key = 4, Value = Footwear Key = 5, Value = Accessories Key 5 exists? True