ภาพรวม
คลาส Dictionary<TKey, TValue> ให้เมธอด ContainsKey() เพื่อตรวจสอบว่าคีย์ (key) มีอยู่ใน Dictionary หรือไม่ คืนค่า true หากพบ false หากไม่พบ
รูปแบบการใช้งาน
Dictionarydict = new Dictionary { {1, "Electronics"}, {2, "Clothing"}, {3, "Toys"} }; bool exists = dict.ContainsKey(2); // true
ตัวอย่างโค้ดเต็ม
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Dictionary d = new Dictionary
{
{1, "Electronics"}, {2, "Clothing"}, {3, "Toys"},
{4, "Footwear"}, {5, "Accessories"}
};
foreach (var kvp in d)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("Key 5 exists? " + d.ContainsKey(5)); // True
}
}
ผลลัพธ์
Key = 1, Value = Electronics Key = 2, Value = Clothing Key = 3, Value = Toys Key = 4, Value = Footwear Key = 5, Value = Accessories Key 5 exists? True
เมธอดที่เกี่ยวข้อง
TryGetValue(key, out value)- ตรวจสอบและดึงค่าในครั้งเดียว (แนะนำ)ContainsValue(value)- ตรวจสอบค่า (ช้ากว่า ContainsKey)dict[key]- ดึงค่าโดยตรง แต่โยน KeyNotFoundException หากไม่มีคีย์