ภาพรวม
เมธอด Dictionary<TKey, TValue>.ContainsKey() ใน C# ใช้ตรวจสอบว่า Dictionary มีคีย์ (key) ที่ระบุอยู่หรือไม่ คืนค่า true หากพบคีย์ และ false หากไม่พบ การค้นหาคีย์มีประสิทธิภาพสูง O(1) เนื่องจาก Dictionary ใช้ Hash Table เป็นโครงสร้างข้อมูลพื้นฐาน
ไวยากรณ์
public bool ContainsKey(TKey key);
พารามิเตอร์
- key - คีย์ที่ต้องการค้นหา
ตัวอย่างที่ 1: พบคีย์ที่ต้องการ
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary dict = new Dictionary();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("จำนวนองค์ประกอบ = " + dict.Count);
Console.WriteLine("\nคู่คีย์/ค่า...");
foreach (KeyValuePair pair in dict)
Console.WriteLine("Key = {0}, Value = {1}", pair.Key, pair.Value);
if (dict.ContainsKey("Three"))
Console.WriteLine("พบคีย์!");
else
Console.WriteLine("ไม่พบคีย์ใน Dictionary!");
dict.Clear();
Console.WriteLine("ล้างคู่คีย์/ค่า...");
Console.WriteLine("จำนวนองค์ประกอบตอนนี้ = " + dict.Count);
}
} ผลลัพธ์ตัวอย่างที่ 1
จำนวนองค์ประกอบ = 5 คู่คีย์/ค่า... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan พบคีย์! ล้างคู่คีย์/ค่า... จำนวนองค์ประกอบตอนนี้ = 0
ตัวอย่างที่ 2: ไม่พบคีย์ที่ต้องการ
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
Dictionary dict = new Dictionary();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("จำนวนองค์ประกอบ = " + dict.Count);
Console.WriteLine("\nคู่คีย์/ค่า...");
foreach (KeyValuePair pair in dict)
Console.WriteLine("Key = {0}, Value = {1}", pair.Key, pair.Value);
if (dict.ContainsKey("mykey"))
Console.WriteLine("พบคีย์!");
else
Console.WriteLine("ไม่พบคีย์ใน Dictionary!");
dict.Clear();
Console.WriteLine("ล้างคู่คีย์/ค่า...");
Console.WriteLine("จำนวนองค์ประกอบตอนนี้ = " + dict.Count);
}
} ผลลัพธ์ตัวอย่างที่ 2
จำนวนองค์ประกอบ = 5 คู่คีย์/ค่า... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan ไม่พบคีย์ใน Dictionary! ล้างคู่คีย์/ค่า... จำนวนองค์ประกอบตอนนี้ = 0
ข้อสังเกตสำคัญ
- ประสิทธิภาพ O(1) - เร็วมาก เหมาะสำหรับการตรวจสอบก่อนเพิ่ม/ดึงข้อมูล
- ควรใช้
ContainsKey()ก่อนTryGetValue()หรือ indexerdict[key]เพื่อหลีกเลี่ยงKeyNotFoundException - การเปรียบเทียบคีย์ใช้
EqualityComparer<TKey>.Default - สำหรับ string key ใช้ ordinal comparison (case-sensitive) โดยค่าเริ่มต้น
- ไม่ควรใช้
ContainsKey()ตามด้วยdict[key]ในสภาพแวดล้อม multi-threaded โดยไม่มี lock (race condition) - ควรใช้TryGetValue()แทน
แนวทางปฏิบัติที่ดี (Best Practice)
// แทนที่จะทำ:
if (dict.ContainsKey(key))
value = dict[key]; // ค้นหา 2 ครั้ง!
// ควรทำ:
if (dict.TryGetValue(key, out var value))
{
// ใช้ value ได้เลย - ค้นหาแค่ 1 ครั้ง
}