Hashtable 数据遍历的几种方式

Hashtable 在集合中称为键值对,它的每一个元素的类型是 DictionaryEntry,由于Hashtable对象的键和值都是Object类型,决定了它可以放任何类型的数据,

下面我就把Hashtable对象中放置定义的一个类的几个对象。

创建的类如下:

代码
1 class Person
2 {
3 private int age;
4 public int Age
5 {
6 get { return age; }
7 set { age = value; }
8 }
9 private string name;
10 public string Name
11 {
12 get { return name; }
13 set { name = value; }
14 }
15 private string email;
16 public string Email
17 {
18 get { return email; }
19 set { email = value; }
20 }
21 }

Hashtable的几种遍历方法如下:

代码
1 static void Main(string[] args)
2 {
3 Person person1 = new Person();
4 person1.Age = 34;
5 person1.Name = "Jacky";
6 person1.Email = "Jacky@gmail.com";
7
8 Person person2 = new Person();
9 person2.Age = 23;
10 person2.Name = "Ajay";
11 person2.Email = "Ajay@gmail.com";
12
13 Person person3 = new Person();
14 person3.Age = 12;
15 person3.Name = "Bill";
16 person3.Email = "Bill@gmail.com";
17
18 Person person4 = new Person();
19 person4.Age = 23;
20 person4.Name = "Gace";
21 person4.Email = "Gace@gmail.com";
22
23 Person person5 = new Person();
24 person5.Age = 45;
25 person5.Name = "Jim";
26 person5.Email = "Jim@gmail.com";
27
28 Hashtable ht = new Hashtable();
29 ht.Add("1", person1);
30 ht.Add("2", person2);
31 ht.Add("3", person3);
32 ht.Add("4", person4);
33 ht.Add("5", person5);
34 Console.WriteLine("请输入你的查询的用户名:");
35 string strName = Console.ReadLine();
36 //第一种方法
37   foreach (string item in ht.Keys)
38 {
39 Person p = (Person)ht[item];
40 if (strName == p.Name)
41 {
42 Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);
43 }
44 }
45
46
47
48 //第二种方法
49   foreach (Person item in ht.Values)
50 {
51 if (item.Name == strName)
52 {
53 Console.WriteLine("查询后的结果是:" + item.Name + "\t" + item.Email + "\t" + item.Age);
54 }
55
56 }
57 //第三种方法
58   foreach (DictionaryEntry item in ht)
59 {
60 if (strName == ((Person)item.Value).Name)
61 {
62 Console.WriteLine("查询后的结果是:" + ((Person)item.Value).Name + "\t" + ((Person)item.Value).Email + "\t" + ((Person)item.Value).Age);
63 }
64 }
65
66 //第四种方法
67   IDictionaryEnumerator id = ht.GetEnumerator();
68 while (id.MoveNext())
69 {
70 Person p = (Person)ht[id.Key];
71 if (p.Name == strName)
72 {
73 Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);
74 }
75 }
76
77 }
怀揣着一点点梦想的年轻人
相信技术和创新的力量
喜欢快速反应的工作节奏
原文地址:https://www.cnblogs.com/hfliyi/p/1944826.html