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

Thuộc tính Count của lớp Hashtable trong C#

Để đếm số phần tử của Hashtable, dùng thuộc tính Count.

Ví dụ

using System;
using System.Collections;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();
            ht.Add("One", "Tom");
            ht.Add("Two", "Jack");
            ht.Add("Three", "Peter");
            ht.Add("Four", "Russel");
            ht.Add("Five", "Brad");
            ht.Add("Six", "Bradley");
            ht.Add("Seven", "Steve");
            ht.Add("Eight", "David");
            
            Console.WriteLine("Count = " + ht.Count);
            Console.ReadKey();
        }
    }
}

Kết quả

Count = 8

Lưu ý: Hashtable cho phép khóa và giá trị là object (non-generic). Ưu tiên dùng Dictionary<TKey, TValue> cho type-safe và hiệu năng tốt hơn.