简单学习Hashtable
- 什么是Hashtable?
Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中keyvalue键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对. 为什么要使用?
(1)数据高频率使用
(2)数据量较大
(3)查询字段包含string类型
(4)包含多种数据类型
3.程序示例
注意引用命名空间:using System.Collections;using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;namespace HashtableExample
{class Program
{
static void Main(string[] args)
{
//声明一个示例对象
Hashtable hashtable = new Hashtable();
//放入key-string
hashtable.Add("a", "hashtable-a");
hashtable.Add("B", "hashtable-B");
hashtable.Add("UserName", "hashtable-UserName");
hashtable.Add("Password", "hashtable-Password");
//放入key-int
hashtable.Add(0, "hashtable-3");
//放入key-模型
hashtable.Add("test", new Test());
Console.WriteLine(hashtable["a"].ToString());
Console.WriteLine(hashtable["B"].ToString());
Console.WriteLine(hashtable["UserName"].ToString());
Console.WriteLine(hashtable["Password"].ToString());
Console.WriteLine(hashtable[0].ToString());
Console.WriteLine(((Test)hashtable["test"]).Name);
Console.WriteLine(((Test)hashtable["test"]).Age);
//测试千万条数据插入
DateTime d1 = DateTime.Now;
for (int i = 1; i <= 1000000; i++)
{
hashtable.Add(i, new Test());
}
Console.WriteLine("插入耗时:"+(DateTime.Now - d1).TotalSeconds+"s");
DateTime d2 = DateTime.Now;
for(int i = 1; i <= 10; i++)
{
Console.WriteLine(((Test)hashtable[i]).Name);
}
Console.WriteLine("取出10条耗时:" + (DateTime.Now - d2).TotalSeconds + "s");
Console.WriteLine(hashtable.Count);
Console.Read();
}
public class Test
{
public Test()
{
Name = "小明";
Age = 10;
}
public string Name { get; set; }
public int Age { get; set; }
}
}
}
还没有评论,来说两句吧...