zoukankan      html  css  js  c++  java
  • [转载]C# HashTable

    一,哈希表(Hashtable)简述

      在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,但排序速度很慢。同时key是区分大小写;value用于存储对应于key的值。Hashtable中keyvalue键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对.

    二,c#中Hashtable用法简述

    1.使用hashtable前.需要添加System.Collections的引用

    using System.Collections; 

    2.添加元素

    Hashtable.Add(key,value);// key,value可以是任何类型

    如果key有重复会掷出运行时异常,你可以这样处理

    if(Hashtable.Contains(key)==false){

    Hashtable.Add(key,value);// 不存在则添加

    }

    也可以这样处理,效率要高些

    try{

    Hashtable.Add(key,value);

    }

    catch{

    // 不处理重复异常

    }

    3.删除元素

    Hashtable.Remove(key);

    4.删除所有

    Hashtable.Clear();

    5.判断键是否已经存在

    Hashtable.Contains(key) // 这个刚才已经用过了

    6.遍历键

    foreach(Object key in Hashtable.Keys){

    }

    7.遍历值

    foreach(Object value in Hashtable.Values){

    }

    8.同时遍历键值对

    foreach(DictionaryEntry de in ht) 

     {

       Console.WriteLine(de.Key);// 取得键

       Console.WriteLine(de.Value);// 取得值

     }

    9.排序键输出(对值也是一样处理)

    ArrayList arraylist = new ArrayList(Hashtable.Keys);

    arraylist.Sort();  

    三,示例代码

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Collections;

    namespace HashtableHelper//命名空间名不可使用类名,如:namespace Hashtable

    {

        class HashtableHelper

        {

            private Hashtable list;

            private Hashtable _list

            {

                set { list = value; }

                get { return list; }

            }

            public HashtableHelper()

            {

                list = new Hashtable();

                Console.WriteLine("-----------Hashtable-------------");

            }

            //添加一个键值对

            public void Add(object key, object value)

            {

                Console.WriteLine("向Hashtable中添加键/值对");

                list.Add(key, value);

                Console.WriteLine("加入\t键:{0}\t值:{1}", key, value);

            }

            //移除一个键值对

            public void Remove(object key)

            {

                Console.WriteLine("从Hashtable中移除键/值对");

                list.Remove(key);

                Console.WriteLine("删除\t键:{0}", key);

            }

            //根据键得到一个键值对

            public void GetValue(object key)

            {

                Console.WriteLine("根据键得到一个键值对");

                Console.WriteLine(string.Format("取值\t键{0}的值:{1}", key, list[key]));

            }

            //判断Hashtable中是否含有某一特定键

            public void Contains(object i)

            {

                Console.WriteLine("判断Hashtable中是否含有某一特定键");

                if (list.Contains(i))

                Console.WriteLine("Hashtable中含有键:{0}",i);

                else

                Console.WriteLine("Hashtable中不含有键:{0}", i);

            }

            //遍历键

            public void GetKeys()

            {

                Console.WriteLine("遍历Hashtable键");

                foreach(object de in list.Keys)

                {

                    Console.WriteLine("\t键:{0}",de);

                }

            }

            //遍历值

            public void GetValues()

            {

                Console.WriteLine("遍历Hashtable值");

                foreach(object de in list.Values)

                {

                    Console.WriteLine("\t值:{0}",de);

                }

            }

            //使用foreach遍历,每一个键/值对是DictionaryEntry类型,注意:逆序遍历

            public void GetKeyValues()

            {

                Console.WriteLine("遍历键/值对");

                foreach (DictionaryEntry de in list)//Dictionary与DictionaryEntry区别

                {

                    Console.WriteLine("\t键:{0}\t值:{1}", de.Key, de.Value);//C#严格区分大小写,如de.key,de.value为错误

                }

            }

            //对Hashtable键排序

            public void Sort()

            {

                Console.WriteLine("对Hashtable键进行排序");

                ArrayList hlist = new ArrayList(list.Keys);

                hlist.Sort();

                for (int i = 0; i < hlist.Count;i++ )

                {

                    Console.WriteLine("\t键:{0}",hlist[i]);

                }

            }

            //清空Hashtable

            public void Clear()

            {

                Console.WriteLine("清空Hashtable");

                list.Clear();

                Console.WriteLine("清空了Hashtable!");

            }

            //获取Hashtable信息

            public void GetInfo()

            {

                Console.WriteLine("获取Hashtable信息");

                Console.WriteLine(string.Format("信息\t元素总数:{0}", list.Count));

            }

        }

    }

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    namespace HashtableHelper

    {

        class Program

        {

            static void Main(string[] args)

            {

                HashtableHelper htb = new HashtableHelper();

                htb.Add(0,"唐玉芳");

                htb.Add(1,"唐玉芳");

                htb.Add(2,"唐玉芳");

                htb.Add(3,"唐玉芳");

                htb.Add(4,"唐玉芳");

                htb.Add(5,"唐玉芳");

                htb.Add(6,"唐玉芳");

                htb.Add(7,"唐玉芳");

                htb.Add(8,"唐玉芳");

                htb.Add(9,"唐玉芳");

                htb.Add(10,"唐玉芳");

                htb.Add(11,"唐玉芳");

                //htb.Add(0,"唐玉芳");

                htb.GetValue(1);

                htb.GetValue(0);

                htb.GetKeys();

                htb.GetValues();

                Console.WriteLine("对Hashtable键排序开始");

                htb.Sort();

                Console.WriteLine("对Hashtable键排序结束");

                htb.GetValues();

                htb.GetKeyValues();

                htb.Contains(111);

                htb.GetInfo();

                htb.Remove(0);

                htb.Remove(0);

                htb.GetValues();

                htb.GetInfo();

                htb.Clear();

                htb.GetInfo();

            }

        }

    }

    注意:对哈希表进行排序在这里的定义是对key/value键值对中的key按一定规则重新排列,但是实际上这个定义是不能实现的,因为我们无法直接在Hashtable进行对key进行重新排列,如果需要Hashtable提供某种规则的输出,可以采用上述变通的做法。

    -------------------------------------------------------------------

     

    1、HashTable定义

    System.Collections. Hashtable类表示键/值对的集合,这些键/值对根据键的哈希代码进行组织, 每个元素都是一个存储在 DictionaryEntry 对象中的键/值对。键不能为 null,但值可以。

    2.优点

    1、通过Key快速查找。

    2、Hashtable 是线程安全的。

    3. Hashtable的构造器

    构造器函数

    注释

    Public Hashtable ()

    使用默认的初始容量(容量大小为0)、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。

    public Hashtable (IDictionary)

    通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。新 Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、哈希代码提供程序和比较器。

    public Hashtable (Int32)

    使用指定的初始容量、默认加载因子、默认哈希代码提供程序和默认比较器来初始化 Hashtable 类的新的空实例。

    4、Hashtable的属性

    属性名

    注释

    Count

    获取包含在 Hashtable 中的键/值对的数目。

    IsFixedSize

    获取一个值,该值指示 Hashtable 是否具有固定大小。

    IsReadOnly

    获取一个值,该值指示 Hashtable 是否为只读。

    Keys

    获取包含 Hashtable 中的键的 ICollection

    Values

    获取包含 Hashtable 中的值的 ICollection。

    5. Hashtable的方法

    方法名

    注释

    Void Add(object key,object value)

    将带有指定键和值的元素添加到 Hashtable 中。

    Void Clear()

    从 Hashtable 中移除所有元素。

    Bool Contains(object key)

    确定 Hashtable 是否包含特定键。

    Bool ContainsKey(object key)

    确定 Hashtable 是否包含特定键。

    Bool ContainsValue(object value)

    确定 Hashtable 是否包含特定值。

    Void Remove(object key)

    从 Hashtable 中移除带有指定键的元素。

    Void InsertRange(int index,Icollection collec)

    用于从指定位置开始添加一批元素,列表后面的元素依次往后移动

    Clone()

    创建 Hashtable 的浅表副本。

    GetObjectData()

    实现 ISerializable 接口,并返回序列化 Hashtable 所需的数据。

     

    6、Hashtable的使用示例

     

    HashTable" alt="C# HashTable" src="https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif">HashTable" alt="C# HashTable" src="http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif" real_src="http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif">代码
    public class Program
    {
    public static void Main(string[] args)
    {
    //创建一个HashTable
    Hashtable openWith = new Hashtable();

    //为HashTable添加元素,不能有重复的key,但可以有重复的值
    openWith.Add("txt", "notepad.exe");
    openWith.Add(
    "bmp", "paint.exe");
    openWith.Add(
    "dib", "paint.exe");
    openWith.Add(
    "rtf", "wordpad.exe");



    //添加重复的key,会抛出异常
    try
    {
    openWith.Add(
    "txt", "winword.exe");
    }
    catch
    {
    Console.WriteLine(
    "An element with Key = \"txt\" already exists.");
    }

    //通过key获得值
    Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

    //重新赋值
    openWith["rtf"] = "winword.exe";
    Console.WriteLine(
    "For key = \"rtf\", value = {0}.", openWith["rtf"]);

    //以赋值的方式,创建一个新元素
    openWith["doc"] = "winword.exe";

    //如果HashTable中不包含该元素,将抛出异常(经测试这里不抛出异常)
    //原因(如果未找到指定的键,尝试获取它将返回 空引用(在 Visual Basic 中为 Nothing),尝试设置它将使用指定的键创建新元素。 )
    try
    {
    Console.WriteLine(
    "For key = \"tif\", value = {0}.", openWith["tif"]);
    }
    catch
    {
    Console.WriteLine(
    "Key = \"tif\" is not found.");
    }

    //判断是否包含特定的key
    if (!openWith.ContainsKey("ht"))
    {
    openWith.Add(
    "ht", "hypertrm.exe");
    Console.WriteLine(
    "Value added for key = \"ht\": {0}", openWith["ht"]);
    }

    //遍历HashTable
    Console.WriteLine();
    foreach (DictionaryEntry de in openWith)
    {
    Console.WriteLine(
    "Key = {0}, Value = {1}", de.Key, de.Value);
    }

    // 获取HashTable中值的集合
    ICollection valueColl = openWith.Values;


    Console.WriteLine();
    foreach (string s in valueColl)
    {
    Console.WriteLine(
    "Value = {0}", s);
    }

    // 获取HashTable中键的集合
    ICollection keyColl = openWith.Keys;


    Console.WriteLine();
    foreach (string s in keyColl)
    {
    Console.WriteLine(
    "Key = {0}", s);
    }


    Console.WriteLine(
    "\nRemove(\"doc\")");
    //移除指定的元素
    openWith.Remove("doc");

    if (!openWith.ContainsKey("doc"))
    {
    Console.WriteLine(
    "Key \"doc\" is not found.");
    }


    Hashtable mySourceHT
    = new Hashtable();
    mySourceHT.Add(
    "A", "valueA");
    mySourceHT.Add(
    "B", "valueB");

    // 创建一个字符串数组
    String[] myTargetArray = new String[15];
    myTargetArray[
    0] = "The";
    myTargetArray[
    1] = "quick";
    myTargetArray[
    2] = "brown";
    myTargetArray[
    3] = "fox";
    myTargetArray[
    4] = "jumped";
    myTargetArray[
    5] = "over";
    myTargetArray[
    6] = "the";
    myTargetArray[
    7] = "lazy";
    myTargetArray[
    8] = "dog";

    // 遍历数组的值
    Console.WriteLine("The target Array contains the following before:");
    PrintValues(myTargetArray,
    ' ');

    //将hashtable中的key复制到数组中
    Console.WriteLine("After copying the keys, starting at index 6:");
    mySourceHT.Keys.CopyTo(myTargetArray,
    6);


    PrintValues(myTargetArray,
    ' ');

    //将hashtable中的Value复制到数组中
    Console.WriteLine("After copying the values, starting at index 6:");
    mySourceHT.Values.CopyTo(myTargetArray,
    6);

    PrintValues(myTargetArray,
    ' ');

    Console.Read();
    }

    //遍历数据方法
    public static void PrintValues(String[] myArr, char mySeparator)
    {
    for (int i = 0; i < myArr.Length; i++)
    Console.Write(
    "{0}{1}", mySeparator, myArr[i]);
    Console.WriteLine();
    }

    }

     

     

    7、Hashtable遍历方法

    方法一

     foreach (System.Collections.DictionaryEntry objDE in objHasTab)
    {
        Console.WriteLine(objDE.Key.ToString());
        Console.WriteLine(objDE.Value.ToString());
    }

     

    方法二

    System.Collections.IDictionaryEnumerator enumerator = objHashTablet.GetEnumerator();
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Key);         // Hashtable关健字
        Console.WriteLine

    }

    8、Hashtable排序

    //把ht的键对象全部复制到ArrayList中

     ArrayList al = new ArrayList(ht.Keys);

     

      al.Sort();//从小到大排列

      //排序完成输出

       for (int i = 0; i < al.Count;i++ )

       {

              object e=al[i];

              object temp = (object)ht[e];//键作为索引器来获得对应的值对象

               Console.WriteLine(temp.tostring());

    }

  • 相关阅读:
    配置文件或者模板中的占位符替换工具类
    [C++设计模式] composite 组合模式
    集群通信组件tribes之集群的平行通信
    hibernate配置
    【Cocos2dx】Windows平台下Cocos2dx 2.x的下载、安装、配置,打造自己的Helloworld
    Codeforces Round #250 (Div. 2)
    一个不断复读且并没什么卵用的我这一种人的 学习观
    2015年创业中遇到的技术问题:81-90
    2015年创业中遇到的技术问题:81-90
    下载好一个android软件之后,怎样自动提示安装?
  • 原文地址:https://www.cnblogs.com/fx2008/p/2236453.html
Copyright © 2011-2022 走看看