管理

Hashtable工具类 - C#小函数类推荐

Posted on 2024-08-06 09:30  lzhdim  阅读(10041)  评论(0编辑  收藏  举报

       此文记录的是一个Hashtable的增强版本,以前没泛型的时候笔者喜欢用Hashtable,性能刚刚的。

/***

    Hashtable工具类

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    Date:   2024-01-15 15:18:00

***/

namespace Lzhdim.LPF.Utility
{
    using System.Collections;

    /// <summary>
    /// The Object inherit of Hashtable
    /// </summary>
    public class HashtableExtend : Hashtable
    {
        /// <summary>
        /// 成员变量
        /// </summary>
        private Hashtable hto = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        public HashtableExtend()
        {
            this.hto = new Hashtable();
        }

        /// <summary>
        /// Add New item
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public override void Add(object key, object value)
        {
            this.hto.Add(key, value);
        }

        /// <summary>
        /// Create a copy Hashtable of the Object
        /// </summary>
        /// <returns></returns>
        public Hashtable Copy()
        {
            Hashtable ht = new Hashtable();

            foreach (DictionaryEntry de in this.hto)
            {
                ht.Add(de.Key, de.Value);
            }

            return ht;
        }

        /// <summary>
        /// Remove a item by key
        /// </summary>
        /// <param name="key"></param>
        public override void Remove(object key)
        {
            this.hto.Remove(key);
        }

        /// <summary>
        /// ASC Sort by key
        /// </summary>
        public void SortByKeyASC()
        {
            ArrayList arrList = new ArrayList(this.hto.Keys);
            arrList.Sort();

            Hashtable ht = new Hashtable();

            for (int i = 0; i < arrList.Count; i++)
            {
                ht.Add(arrList[i], this.hto[arrList[i]]);
            }

            this.hto.Clear();
            this.hto = ht;
        }

        /// <summary>
        /// DESC Sort by key
        /// </summary>
        public void SortByKeyDESC()
        {
            ArrayList arrList = new ArrayList(this.hto.Keys);
            arrList.Sort();

            Hashtable ht = new Hashtable();

            for (int i = arrList.Count - 1; i >= 0; i++)
            {
                ht.Add(arrList[i], this.hto[arrList[i]]);
            }

            this.hto.Clear();
            this.hto = ht;
        }
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved