首页 > 代码库 > HashTable集合遍历的三种方法
HashTable集合遍历的三种方法
hashtable集合遍历可以根据key,value以及key+value
示例代码:
Hashtable table = new Hashtable();
Student stu = new Student();
stu.Name = "李四";
stu.Age = 18;
Student stu1 = new Student();
stu1.Name = "张三";
stu1.Age = 18;
Student stu2 = new Student();
stu2.Name = "张飞";
stu2.Age = 18;
table.Add(stu.Name, stu);
table.Add(stu1.Name, stu);
table.Add(stu2.Name, stu);
//HashTable集合遍历的三种方法
//方法一: 根据key值进行遍历
foreach (string item in table.Keys)
{
Console.WriteLine("key为" + item);
Student stu4 = (Student)table[item];
Console.WriteLine(stu4.Name);
}
Console.WriteLine("===================================");
//方法二: 根据values值进行遍历
foreach (Student student in table.Values)
{
Console.WriteLine(student.Name);
}
Console.WriteLine("---------------------------------");
//方法三:根据values和key进行遍历
foreach (DictionaryEntry item in table)
{
Console.WriteLine("key是{0}\tvalue是{1}", item.Key, ((Student)item.Value).Name);
}
HashTable集合遍历的三种方法