C#中HashTable相关方法

C#中的哈希表(HashTable)是由一些列哈希代码组构起的键值对,用于提高访问元素的效率,可以使用键来访问值,键和值都属于Object类型的变量,它同样提供增删查改和多种遍历操作。

cs 复制代码
using System;
using System.Collections;

namespace lesson04
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable hashtable = new Hashtable();

            #region 增删查改
            //增加(不允许出现相同的键)
            hashtable.Add(1, "123");
            hashtable.Add(2, "456");
            hashtable.Add(3, "789");
            hashtable.Add("999", 45);
            //删除
            hashtable.Remove(999);
            //清空
            //hashtable.Clear();
            //查找(找不到返回null)
            Console.WriteLine(hashtable[3]);
            //查找键或值是否在哈希表中
            if (hashtable.Contains(2)) 
            {
                Console.WriteLine("存在键为2的键值对");
            }
            if (hashtable.ContainsKey(3)) 
            {
                Console.WriteLine("存在键为3的键值对");
            }
            if (hashtable.ContainsValue("123")) 
            {
                Console.WriteLine("存在键为123的键值对");
            }
            //修改(仅允许修改值内容)
            hashtable[0] = 100.5f;
            Console.WriteLine("********************");
            #region 遍历
            Console.WriteLine(hashtable.Count);
            //1,遍历所有键
            foreach (object item in hashtable.Keys)
            {
                Console.WriteLine("键 = " + item);
                Console.WriteLine("值 = " +hashtable[item]);//顺带遍历值
            }
            Console.WriteLine("********************");
            //2.遍历所有值
            foreach (object item in hashtable.Values)
            {
                Console.WriteLine("值 = " + item);
            }
            Console.WriteLine("********************");
            //3.同时遍历键值对
            foreach (DictionaryEntry item in hashtable)
            {
                Console.WriteLine("键 = " + item.Key + "值 = " + item.Value);
            }
            //4.迭代器遍历
            IDictionaryEnumerator myEnumerator = hashtable.GetEnumerator();
            bool flag = myEnumerator.MoveNext();
            while (flag) 
            {
                Console.WriteLine("键 = " + myEnumerator.Key + "值 = " + myEnumerator.Value);
                flag = myEnumerator.MoveNext();
            }
            #endregion
            #endregion
        }
    }
}
相关推荐
rockey6272 分钟前
AScript正式推出Template模板引擎
c#
geovindu43 分钟前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
沐言Agent2 小时前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
炸膛坦客4 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++
夜不会漫长5 小时前
C++:C++11特性
开发语言·c++·算法
apcipot_rain6 小时前
C++转java日记(13)
java·开发语言
郝学胜-神的一滴6 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio7 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
星恒随风7 小时前
从0实现C++ AI大模型接入SDK(五):DeepSeekProvider的实现——策略模式、HTTP请求与SSE流式响应
linux·开发语言·c++·人工智能
饮水桶_T8 小时前
Git笔记
开发语言·笔记·算法