哈希表的简单使用

常见功能
哈希表中添加一个key/键值对:HashtableObject.Add(key,);
哈希表中去除某个key/键值对:HashtableObject.Remove(key);
哈希表中移除所有元素: HashtableObject.Clear();
判断哈希表是否包含特定键key: HashtableObject.Contains(key);
 
测试用例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; //哈希表引用

namespace HashTableTest
{
    class TestMain
    {
        static void Main(string[] args)
        {
            Hashtable ht = new Hashtable(); //创建哈希实例
            ht.Add("E","e"); //ht.Add(key,value) key唯一,value可以重复
            ht.Add("A", "a");
            ht.Add("C", "c");
            ht.Add("B", "b");

            string str = (string)ht["A"];
            Console.WriteLine(str); //输出a

            Console.WriteLine("---------遍历哈希表---------");
            foreach (DictionaryEntry entry in ht)
            {
                Console.Write(entry.Key + ":");
                Console.WriteLine(entry.Value);
            }

            Console.WriteLine("--------哈希表排序---------");
            ArrayList array = new ArrayList(ht.Keys);
            array.Sort(); //按字母排序
            foreach (string strKey in array)
            {
                Console.Write(strKey + ":");
                Console.WriteLine(ht[strKey]); //排序输出
            }

            if (ht.Contains("E")) //判断哈希表是否包含特定键,其返回值为true或false
            {
                Console.WriteLine("键值为E存在!");
            }
            ht.Remove("C");
            if (!ht.ContainsKey("C"))
            {
                Console.WriteLine("键值为C被移除!");
            }

            Console.WriteLine(ht["A"]); //输出a

            ht.Clear(); //移除所有元素
        }
    }
}
View Code

测试结果:

 
要么忍,要么狠,要么滚!
原文地址:https://www.cnblogs.com/zxd543/p/3307092.html