Hashtable 数据遍历的几种方式
Hashtable 在集合中称为键值对,它的每一个元素的类型是 DictionaryEntry,由于Hashtable对象的键和值都是Object类型,决定了它可以放任何类型的数据,
下面我就把Hashtable对象中放置定义的一个类的几个对象。
创建的类如下:
代码
class Person
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
}
Hashtable的几种遍历方法如下:
代码
static void Main(string[] args)
{
Person person1 = new Person();
person1.Age = 34;
person1.Name = "Jacky";
person1.Email = "Jacky@gmail.com";
Person person2 = new Person();
person2.Age = 23;
person2.Name = "Ajay";
person2.Email = "Ajay@gmail.com";
Person person3 = new Person();
person3.Age = 12;
person3.Name = "Bill";
person3.Email = "Bill@gmail.com";
Person person4 = new Person();
person4.Age = 23;
person4.Name = "Gace";
person4.Email = "Gace@gmail.com";
Person person5 = new Person();
person5.Age = 45;
person5.Name = "Jim";
person5.Email = "Jim@gmail.com";
Hashtable ht = new Hashtable();
ht.Add("1", person1);
ht.Add("2", person2);
ht.Add("3", person3);
ht.Add("4", person4);
ht.Add("5", person5);
Console.WriteLine("请输入你的查询的用户名:");
string strName = Console.ReadLine();
//第一种方法
foreach (string item in ht.Keys)
{
Person p = (Person)ht[item];
if (strName == p.Name)
{
Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);
}
}
//第二种方法
foreach (Person item in ht.Values)
{
if (item.Name == strName)
{
Console.WriteLine("查询后的结果是:" + item.Name + "\t" + item.Email + "\t" + item.Age);
}
}
//第三种方法
foreach (DictionaryEntry item in ht)
{
if (strName == ((Person)item.Value).Name)
{
Console.WriteLine("查询后的结果是:" + ((Person)item.Value).Name + "\t" + ((Person)item.Value).Email + "\t" + ((Person)item.Value).Age);
}
}
//第四种方法
IDictionaryEnumerator id = ht.GetEnumerator();
while (id.MoveNext())
{
Person p = (Person)ht[id.Key];
if (p.Name == strName)
{
Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);
}
}
}
posted on 2015-11-27 17:17 kebizhanmushi 阅读(168) 评论(0) 编辑 收藏 举报