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

ตรวจสอบว่า Hashtable มีคีย์เฉพาะหรือไม่ใน C#

ภาพรวม

Hashtable.Contains(Object key) ตรวจสอบว่ามีคีย์ที่ระบุในแฮชเทเบิลหรือไม่ คืน bool

ตัวอย่าง 1: Hashtable ขนาดใหญ่

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Hashtable hash = new Hashtable();
        hash.Add("One", "Katie");
        hash.Add("Two", "John");
        hash.Add("Three", "Barry");
        hash.Add("Four", "");
        hash.Add("Five", "Harry");
        hash.Add("Six", "F");
        hash.Add("Seven", "Tom");
        hash.Add("Eight", "Andy");
        hash.Add("Nine", "I");
        hash.Add("Ten", "Tim");

        Console.WriteLine("Hashtable Key and Value pairs...");
        foreach (DictionaryEntry entry in hash) {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }

        Console.WriteLine("Is the Hashtable having fixed size? = " + hash.IsFixedSize);
        Console.WriteLine("If Hashtable read-only? = " + hash.IsReadOnly);
        Hashtable hash2 = Hashtable.Synchronized(hash);
        Console.WriteLine("Is Hash synchronized = " + hash2.IsSynchronized);
        Console.WriteLine("Does Hashtable contains the key Ten = " + hash.Contains("Ten"));
    }
}

ผลลัพธ์ตัวอย่าง 1

Hashtable Key and Value pairs...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and
Eight and Andy
Nine and I
Six and F
Is the Hashtable having fixed size? = False
If Hashtable read-only? = False
Is Hash synchronized = True
Does Hashtable contains the key Ten = True

ตัวอย่าง 2: คีย์ไม่มีอยู่

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Hashtable hash = new Hashtable();
        hash.Add("1", "AB");
        hash.Add("2", "BC");
        hash.Add("3", "DE");
        hash.Add("4", "EF");
        hash.Add("5", "GH");
        hash.Add("6", "IJ");
        hash.Add("7", "KL");
        hash.Add("8", "MN");
        hash.Add("9", "OP");
        hash.Add("10", "QR");

        Console.WriteLine("Value at key 3 = " + hash["3"]);
        Console.WriteLine("Does Hashtable contains the key 12 = " + hash.Contains("12"));
    }
}

ผลลัพธ์ตัวอย่าง 2

Value at key 3 = DE
Does Hashtable contains the key 12 = False

สรุป

  • Contains(key) ตรวจสอบคีย์ (ไม่ใช่ค่า)
  • ใช้ ContainsValue ถ้าต้องการตรวจสอบค่า
  • Hashtable.Synchronized สร้าง wrapper thread-safe