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

ล้าง Hashtable ใน C#

ล้าง Hashtable โดยใช้เมธอด Clear() ใน C#

นี่คือ Hashtable ของเรา:

Hashtable h = new Hashtable();
h.Add(1, "Amit");
h.Add(2, "Sachin");
h.Add(3, "Rahul");

ใช้เมธอด clear:

h.Clear();

ถ้าคุณลองแสดง Hashtable ตอนนี้ จะไม่มีอะไรแสดง เพราะ Hashtable ว่างแล้ว

ตัวอย่าง

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable h = new Hashtable();
        h.Add(1, "Amit");
        h.Add(2, "Sachin");
        h.Add(3, "Rahul");
        
        Console.WriteLine("Keys and Values list:");
        foreach (var key in h.Keys)
        {
            Console.WriteLine("Key = {0}, Value = {1}", key, h[key]);
        }
        
        // ล้างคู่คีย์-ค่าทั้งหมด
        Console.WriteLine("The Hashtable key and Value Pairs are empty now...");
        h.Clear();
        
        foreach (var key in h.Keys)
        {
            Console.WriteLine("Key = {0}, Value = {1}", key, h[key]);
        }
    }
}

ผลลัพธ์

Keys and Values list:
Key = 3, Value = Rahul
Key = 2, Value = Sachin
Key = 1, Value = Amit
The Hashtable key and Value Pairs are empty now...