前两天学习了下HashTable遍历数据的方法,借鉴了网上的一些资料,整理发表出来,共同学习。。。
遍历HashTable可以通过一下几种方法:key/value/DictionaryEntry/IDictionaryEnumerator
以下是实现代码:
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; }
}
}
static void Main(string[] args)
{
Person p1 = new Person();
p1.Age = 13;
p1.Name = "zhangsan";
p1.Email = "zhangsan@gmail.com";
Person p2 = new Person();
p2.Age = 14;
p2.Name = "lisi";
p2.Email = "lisi@gmail.com";
Person p3 = new Person();
p3.Age = 15;
p3.Name = "wangwu";
p3.Email = "wangwu@gmail.com";
Hashtable ht = new Hashtable();
ht.Add("1", p1);
ht.Add("2", p2);
ht.Add("3", p3);
//方法一:遍历HashTable的key输出
foreach (string item in ht.Keys)
{
Person p = (Person)ht[item];
Console.Write(p.Name + "\t" + p.Age + "\t" + p.Email);
}
//方法二:遍历HashTable的value输出
foreach (Person item in ht.Values)
{
Console.Write(item.Name + "\t" + item.Age + "\t" + item.Email);
}
//方法三:通过DictionaryEntry来输出
foreach (DictionaryEntry item in ht)
{
Console.Write(((Person)item.Value).Name + "\t" + ((Person)item.Value).Age + "\t" + ((Person)item.Value).Email);
}
//方法四:通过IDictionaryEnumerator来输出
IDictionaryEnumerator id = ht.GetEnumerator();
while (id.MoveNext())
{
Person p = (Person)ht[id.Key];
Console.Write(p.Name + "\t" + p.Age + "\t" + p.Email);
}
}