Hashtable
在System.Collection是命名空间李Hashtable是程序员经常用到的类,它以快速检索著称,是研发人员开发当中不可缺少的利器。
Hashtable表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。Hashtable的键必须是唯一的,没有有效的排序,他进行的是内在的排序。
Hashtable有以下4中遍历方式:
1、以string对象为键值遍历哈希表。
2、以自定义对象为键值遍历哈希表。
3、以DictionaryEntry对象为键值遍历哈希表。
4、通过继承IDictionaryEnumerator接口的对象来遍历哈希表。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
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)
{
var a = new Person
{
Age = 34,
Name = "Jacky",
Email = "Jacky@gmail.com"
};
var b = new Person
{
Age = 23,
Name = "Ajay",
Email = "Ajay@gmail.com"
};
var c = new Person
{
Age = 12,
Name = "Bill",
Email = "Bill@gmail.com"
};
var d = new Person
{
Age = 23,
Name = "Gace",
Email = "Gace@gmail.com"
};
var e = new Person
{
Age = 45,
Name = "Jim",
Email = "Jim@gmail.com"
};
var ht = new Hashtable
{
{ "1", a },
{ "2", b },
{ "3", c },
{ "4", d },
{ "5", e }
};
Console.WriteLine("请输入你的查询的用户名:");
var strName = Console.ReadLine();
//第一种方法
foreach (string item in ht.Keys)
{
var p = (Person)ht[item];
if (strName == p.Name)
{
Console.WriteLine("查询后的结果是:" + p.Name + "\t" + p.Email + "\t" + p.Age);
}
}
Console.WriteLine("华丽的分割线=========================================================");
//第二种方法
foreach (Person item in ht.Values)
{
if (item.Name == strName)
{
Console.WriteLine("查询后的结果是:" + item.Name + "\t" + item.Email + "\t" + item.Age);
}
}
Console.WriteLine("华丽的分割线=========================================================");
//第三种方法
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);
}
}
Console.WriteLine("华丽的分割线=========================================================");
//第四种方法
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);
}
}
Console.ReadKey();
}
}
}