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();
}
}
}