C#基础(17)——Hashtable
来源:互联网 发布:淘宝隐藏优惠券网站 编辑:程序博客网 时间:2024/06/07 01:08
1、Hashtable简介
Hashtable称为键值对集合,类似于Python的字典 ,根据键去找值的。
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace HashTable集合{ class Program { static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add(1, "张三"); ht.Add(false, "错误"); ht.Add(2, "s3"); //var推断类型,必须赋初值 //C#是一门强类型语言,在代码中必须对每一个变量的类型进行明确的定义 //js是一门弱类型语言,不需要定义类型 foreach (var item in ht.Keys)//遍历键 {//效率高于for循环 Console.WriteLine("{0}--->{1}",item,ht[item]); } Console.ReadKey(); } }}
2、键值对的添加
键必须唯一,值可以重复,添加方式:
Hashtable ht = new Hashtable(); ht.Add(1, "张三"); ht.Add(false, "错误"); ht.Add(2, "s3"); ht[6] = "新来的";
添加已有的,Add会报错,而修改操作:
3、判断已有的键
Hashtable ht = new Hashtable(); ht.Add(1, "张三"); ht.Add(false, "错误"); ht.Add(2, "s3"); ht[6] = "新来的"; ht[6] = "把新来的干掉"; //var推断类型,必须赋初值 //C#是一门强类型语言,在代码中必须对每一个变量的类型进行明确的定义 //js是一门弱类型语言,不需要定义类型 if (!ht.ContainsKey(2))//不包含时 { ht.Add(2, "顶顶顶顶"); } else { Console.WriteLine("已经包含这个key键"); }
清空操作:
ht.Clear
删除操作:
ht.Remove(2);
4、Hashtable练习
大写转换为小写:
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace HashTable集合{ class Program { private const string Alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private const string alpha = "abcdefghijklmnopqrstuvwxyz"; private static string str; static void Main(string[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < Alpha.Length; i++) { ht[Alpha[i]] = alpha[i]; } //foreach (var item in ht.Keys) //{ // Console.WriteLine("{0}-->{1}", item, ht[item]); //} Console.WriteLine("请输入大写字母:"); string input = Console.ReadLine(); for (int i = 0; i < input.Length; i++) { if (ht.ContainsKey(input[i]))//一定要字符input[i],不是字符串 { str += ht[input[i]].ToString(); } else { str += input[i]; } } Console.WriteLine(">>>{0}", str); Console.ReadKey(); } }}
阅读全文
0 0
- C#基础(17)——Hashtable
- C#基础 之 Hashtable
- C#基础(18)——List泛型集合、装箱、拆箱、字典集合与Hashtable区别
- C#基础课程之五集合(HashTable,Dictionary)
- C#技巧—哈希表Hashtable用法
- C# 哈希表(Hashtable)
- C# Hashtable(哈希表)
- Java基础——HashTable源码分析
- c#之哈希表(Hashtable)
- C# HashTable
- C# Hashtable
- C# Hashtable
- C# hashtable
- C# Hashtable
- C# Hashtable
- C# HashTable
- c# hashtable
- C# Hashtable
- 1.8 输出浮点数
- 51NOD 最复杂的数 暴力(反素数)
- Lightoj1071:Baker Vai(最小费用最大流)
- Java 集合Collection
- 12c undo 表空间的管理
- C#基础(17)——Hashtable
- opencv实现两幅图片的加权融合
- Nginx HLS压测工具之vegeta
- 1.9 字符三角形
- java类似增量指针的操作
- github 创建远程分支以及远程分支无法删除的问题解决
- CodeForces Gym 101615简要题解
- 1.10字符菱形
- 不允许指针指向不完整的类类型