C#中HashTable的遍历

时间:2022-04-05 16:12:29

1. HashTable 存储的是无序的,也就是最先存储的键/值对不一定在第一个位置上;

2. HashTable 存储的是弱类型的,也就是要由自己来控制存储类型,并且取值时要进行强制类型转换。

  由于HashTable只能通过键名来访问,不能通过索引访问,所以遍历的时候只能用foreach循环,遍历的时候

可分三种情况:

  (1)遍历Keys,获取HashTable中的所有键;

  (2)遍历Values,获取HashTable中的所有值;

  (3)遍历Keys/Values,获取HashTable中的所有键/值对。

  详细说明见如下Demo:

    public class AddressDemo
    {
        /// <summary>
        /// 构造函数的重载
        /// </summary>
        public AddressDemo() : this("张三", "地址不详") { }
        public AddressDemo(string name) : this(name, "地址不详") { }
        public AddressDemo(string name, string address)
        {
            this.Name = name;
            this.Address = address;
        }

        //姓名
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        //地址
        private string address;
        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        //显示地址的方法
        public void DisplayAddress()
        {
            string message = string.Format(@"{0} 同学的家庭住址在 {1}",this.Name,this.Address);
            Console.WriteLine(message);
            Console.WriteLine();
        }
    }

 

    class Program
    {
        static void Main(string[] args)
        {
            Hashtable address = new Hashtable(); //定义地址集合

            AddressDemo zhangSan = new AddressDemo("张三", "深圳市龙华新区");
            AddressDemo liSi = new AddressDemo("李四", "深圳市福田区");

            //往集合中添加对象
            address.Add(zhangSan.Name, zhangSan);
            address.Add(liSi.Name, liSi);

            //获取集合中的元素
            AddressDemo addLiSi = (AddressDemo)address["李四"];
            addLiSi.DisplayAddress();

            //第(1)种情况,遍历集合中的Keys
            Console.WriteLine("集合中的Key:");
            foreach (Object ad in address.Keys)
            {
                Console.WriteLine(ad.ToString());
            }
            Console.WriteLine();

            //第(2)种情况,遍历集合中的Values
            Console.WriteLine("集合中的Value:");
            foreach (Object ad in address.Values)
            {
                AddressDemo ad1=(AddressDemo)ad;
                Console.WriteLine(ad1.Name + "\t" + ad1.Address);
            }
            Console.WriteLine();

            //第(3)种情况,遍历集合中的Keys/Values
            Console.WriteLine("集合中的Key/Value:");
            foreach (DictionaryEntry ad in address)
            {
                Console.Write(ad.Key+":\t");
                AddressDemo ad1 = (AddressDemo)ad.Value;
                Console.WriteLine(ad1.Name+"\t"+ad1.Address);
            }
        }
    }

 

运行结果如下: 

C#中HashTable的遍历