Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa phần tử theo khóa khỏi Hashtable trong C#

Giới thiệu

Phương thức Remove(object key) của Hashtable xóa cặp khóa-giá trị ứng với khóa cho trước. Nếu khóa không tồn tại, không làm gì (không ném exception).

Ví dụ 1: Xóa khóa "5" khỏi 10 phần tử

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable(10);
        hash.Add("1", "A");
        hash.Add("2", "B");
        hash.Add("3", "C");
        hash.Add("4", "D");
        hash.Add("5", "E");
        hash.Add("6", "F");
        hash.Add("7", "G");
        hash.Add("8", "H");
        hash.Add("9", "I");
        hash.Add("10", "J");

        Console.WriteLine("Các cặp khóa-giá trị Hashtable...");
        foreach (DictionaryEntry entry in hash)
        {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }

        Console.WriteLine("Hashtable có kích thước cố định? = " + hash.IsFixedSize);
        Console.WriteLine("Số entry Hashtable = " + hash.Count);

        hash.Remove("5");

        Console.WriteLine("Số entry Hashtable (cập nhật) = " + hash.Count);
    }
}

Kết quả

Các cặp khóa-giá trị Hashtable...
10 and J
1 and A
2 and B
3 and C
4 and D
5 and E
6 and F
7 and G
8 and H
9 and I
Hashtable có kích thước cố định? = False
Số entry Hashtable = 10
Số entry Hashtable (cập nhật) = 9

Ví dụ 2: Xóa nhiều khóa

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable(10);
        hash.Add("One", "Marketing");
        hash.Add("Two", "Operations");
        hash.Add("Three", "Finance");
        hash.Add("Four", "IT");
        hash.Add("Five", "Sales");
        hash.Add("Six", "Purchase");

        Console.WriteLine("Các cặp khóa-giá trị Hashtable...");
        foreach (DictionaryEntry entry in hash)
        {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }

        Console.WriteLine("Số entry Hashtable = " + hash.Count);
        hash.Remove("Two");
        hash.Remove("Three");
        hash.Remove("Four");
        Console.WriteLine("Số entry Hashtable (cập nhật) = " + hash.Count);
    }
}

Kết quả

Các cặp khóa-giá trị Hashtable...
One and Marketing
Five and Sales
Three and Finance
Two and Operations
Four and IT
Six and Purchase
Số entry Hashtable = 6
Số entry Hashtable (cập nhật) = 3

Lưu ý

  • Hashtable không generic, khóa và giá trị kiểu object.
  • Để xóa tất cả: Clear().
  • Trong code hiện đại, dùng Dictionary<TKey, TValue> hoặc ConcurrentDictionary<TKey, TValue>.