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

Lấy enumerator duyệt Hashtable trong C#

Giới thiệu

Phương thức GetEnumerator() của Hashtable trả về IDictionaryEnumerator cho phép duyệt các cặp khóa-giá trị (DictionaryEntry). Thứ tự duyệt không xác định.

Ví dụ 1: Hashtable 10 entry, duyệt enumerator

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);

        Console.WriteLine("\nEnumerator duyệt Hashtable...");
        IDictionaryEnumerator demoEnum = hash.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        hash.Clear();
    }
}

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
Enumerator duyệt Hashtable...
Key = 10, Value = J
Key = 1, Value = A
Key = 2, Value = B
Key = 3, Value = C
Key = 4, Value = D
Key = 5, Value = E
Key = 6, Value = F
Key = 7, Value = G
Key = 8, Value = H
Key = 9, Value = I

Ví dụ 2: Hashtable 6 entry

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable(10);
        hash.Add("One", "A");
        hash.Add("Two", "B");
        hash.Add("Three", "C");
        hash.Add("Four", "D");
        hash.Add("Five", "E");
        hash.Add("Six", "F");

        Console.WriteLine("Các cặp khóa-giá trị Hashtable...");
        Console.WriteLine("\nEnumerator duyệt Hashtable...");
        IDictionaryEnumerator demoEnum = hash.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        hash.Clear();
    }
}

Kết quả

Các cặp khóa-giá trị Hashtable...
Enumerator duyệt Hashtable...
Key = One, Value = A
Key = Five, Value = E
Key = Three, Value = C
Key = Two, Value = B
Key = Four, Value = D
Key = Six, Value = F

Lưu ý

  • IDictionaryEnumerator có Key, Value, Entry (DictionaryEntry).
  • Duyệt foreach trên Hashtable cũng dùng enumerator này ngầm.
  • Không sửa đổi Hashtable khi đang enumerate (ném InvalidOperationException).
  • Generic: Dictionary<TKey, TValue> dùng IEnumerator<KeyValuePair<TKey, TValue>>.