Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบค่าใน SortedList ด้วย ContainsValue() ใน C#


เมธอด SortedList.ContainsValue() ใน C# ใช้สำหรับตรวจสอบว่า SortedList มีค่า (Value) ที่ระบุอยู่หรือไม่ คืนค่า true หากพบ มิฉะนั้น false

ตัวอย่างที่ 1: ค้นหาค่าที่มีอยู่

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        SortedList list = new SortedList();
        list.Add("1", "One");
        list.Add("2", "Two");
        list.Add("3", "Three");
        list.Add("4", "Four");
        list.Add("5", "Five");
        list.Add("6", "Six");
        list.Add("7", "Seven");
        list.Add("8", "Eight");

        Console.WriteLine("Key and Value of SortedList....");
        foreach (DictionaryEntry k in list)
        {
            Console.WriteLine("Key: {0}, Value: {1}", k.Key, k.Value);
        }

        Console.WriteLine("Is the SortedList having the value? " + list.ContainsValue("Five"));
    }
}

ผลลัพธ์

Key and Value of SortedList....
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four
Key: 5, Value: Five
Key: 6, Value: Six
Key: 7, Value: Seven
Key: 8, Value: Eight
Is the SortedList having the value? True

ตัวอย่างที่ 2: ค้นหาค่าที่ไม่มีอยู่

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        SortedList list = new SortedList();
        list.Add("1", "One");
        list.Add("2", "Two");
        list.Add("3", "Three");
        list.Add("4", "Four");
        list.Add("5", "Five");
        list.Add("6", "Six");
        list.Add("7", "Seven");
        list.Add("8", "Eight");

        Console.WriteLine("Key and Value of SortedList....");
        foreach (DictionaryEntry k in list)
        {
            Console.WriteLine("Key: {0}, Value: {1}", k.Key, k.Value);
        }

        Console.WriteLine("Is the SortedList having the value? " + list.ContainsValue("Tenth"));
    }
}

ผลลัพธ์

Key and Value of SortedList....
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four
Key: 5, Value: Five
Key: 6, Value: Six
Key: 7, Value: Seven
Key: 8, Value: Eight
Is the SortedList having the value? False

ข้อสังเกตสำคัญ

  • ContainsValue() ค้นหาแบบ Linear Search — O(n)
  • ใช้ Equals() ในการเปรียบเทียบค่า
  • SortedList จัดเก็บ Key-Value pairs เรียงตาม Key — แต่ ContainsValue ไม่ได้ใช้ประโยชน์จากการเรียง
  • หากต้องการค้นหา Key ใช้ ContainsKey() (O(log n) เนื่องจาก Binary Search)
  • เวอร์ชัน Generic SortedList<TKey, TValue>.ContainsValue(TValue) ทำงานเหมือนกัน