ภาพรวม
เมธอด Dictionary<TKey, TValue>.ContainsValue() ใน C# ใช้ตรวจสอบว่า Dictionary มีค่า (value) ที่ระบุอยู่หรือไม่ คืนค่า true หากพบค่าดังกล่าว และ false หากไม่พบ การค้นหาจะทำแบบ linear search (O(n)) เพราะ Dictionary จัดทำดัชนีโดยคีย์ (key) ไม่ใช่ค่า
ไวยากรณ์
public bool ContainsValue(TValue value);
พารามิเตอร์
- value - ค่าที่ต้องการค้นหา
ตัวอย่างที่ 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.ContainsValue("Kevin"))
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", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
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.ContainsValue("Angelina"))
Console.WriteLine("พบค่า!");
else
Console.WriteLine("ไม่พบค่าใน Dictionary!");
dict.Clear();
Console.WriteLine("ล้างคู่คีย์/ค่า...");
Console.WriteLine("จำนวนองค์ประกอบตอนนี้ = " + dict.Count);
}
} ผลลัพธ์ตัวอย่างที่ 2
จำนวนองค์ประกอบ = 5 คู่คีย์/ค่า... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan ไม่พบค่าใน Dictionary! ล้างคู่คีย์/ค่า... จำนวนองค์ประกอบตอนนี้ = 0
ข้อสังเกตสำคัญ
- การค้นหาค่า (value) ใช้เวลา O(n) ในขณะที่การค้นหาคีย์ (key) ด้วย
ContainsKey()ใช้เวลา O(1) - หากต้องการค้นหาค่าบ่อยครั้ง ควรพิจารณาสร้าง Dictionary ใหม่ที่สลับ Key/Value หรือใช้
Lookup - การเปรียบเทียบค่าใช้
EqualityComparer<TValue>.Default(สำหรับ reference type ใช้ reference equality) - ค่า
nullสามารถค้นหาได้ หาก TValue เป็น reference type หรือ nullable value type