hastable相关问题
hastable就像是一个特殊的数组,它有一个类似主键的唯一编号(类似数组[]中的数字,这个键值是你随便写的),和这个唯一编号又对应一个值value(值的数据类型是不受限制的)
下面是一个适用hashtable类的例子:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace 练习
{
public class name
{
Hashtable hs = new Hashtable();
public void hashtable()
{
hs.Add("001","周杰伦87992352");
hs.Add("002","张娜拉87993952");
hs.Add("003","刘德华87993723");
foreach (DictionaryEntry dr in hs)//通过DictionaryEntry遍历hashtable
{
string key = (string)dr.Key;
string value = (string)dr.Value;
Console.WriteLine("编号为"+key+" 的号码为:");
}
hs.Remove("003");//移除键值为003的记录
if (!hs.Contains("003"))
{ Console.WriteLine("电话簿中不存在编号为003的记录"); }
else
{ Console.WriteLine((string)hs["003"]); }
if (!hs.ContainsValue("刘德华87993723"))
{ hs.Add("003", "刘德华87993723"); }
else
{ Console.WriteLine("记录已经存在"); }
foreach (string skey in hs.Keys) //通过键集合来遍历hashtable
{ Console.WriteLine((string)hs[skey]); }
}
public static void Main(String[] args)
{
name n = new name();
n.hashtable();
}
}
}
下面是一个适用hashtable类的例子:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace 练习
{
public class name
{
Hashtable hs = new Hashtable();
public void hashtable()
{
hs.Add("001","周杰伦87992352");
hs.Add("002","张娜拉87993952");
hs.Add("003","刘德华87993723");
foreach (DictionaryEntry dr in hs)//通过DictionaryEntry遍历hashtable
{
string key = (string)dr.Key;
string value = (string)dr.Value;
Console.WriteLine("编号为"+key+" 的号码为:");
}
hs.Remove("003");//移除键值为003的记录
if (!hs.Contains("003"))
{ Console.WriteLine("电话簿中不存在编号为003的记录"); }
else
{ Console.WriteLine((string)hs["003"]); }
if (!hs.ContainsValue("刘德华87993723"))
{ hs.Add("003", "刘德华87993723"); }
else
{ Console.WriteLine("记录已经存在"); }
foreach (string skey in hs.Keys) //通过键集合来遍历hashtable
{ Console.WriteLine((string)hs[skey]); }
}
public static void Main(String[] args)
{
name n = new name();
n.hashtable();
}
}
}