如何制作一个包含三个参数的hashTable
?我想使用 hashTable
和 dictionary
存储电话号码、姓名和地址。电话号码作为键,姓名、地址作为其值。但我只能输入两个数据,电话号码和姓名。如何在 hashTable
中保存电话号码、姓名、地址?
Hashtable phoneBook;
public FrmPhoneBook()
{
InitializeComponent();
phoneBook = new Hashtable();
}
public void addNewPhoneBook(string name, string tel, string add)
{
string names = name;
string telp = tel;
string address = add;
if (!phoneBook.ContainsKey(telp))
{
phoneBook.Add(telp, names);
getDetails();
}
}
public void getDetails()
{
lvDetails.Items.Clear();
foreach (DictionaryEntry values in phoneBook)
{
lvDetails.Items.Add(values.Value.ToString());
lvDetails.Items[lvDetails.Items.Count - 1].SubItems.Add(
values.Key.ToString());
}
}
最佳答案
您可以将键作为电话号码,并将值作为一个结构,该结构具有两个成员,一个是地址,一个是姓名。还可以考虑转向 Dictionary,因为它是类型安全的
struct User
{
public string Name;
public string Address;
}
static void Main(string[] args)
{
Dictionary<string, User> hash = new Dictionary<string, User>();
//To add to the hash
hash.Add( "22255512282" ,
new User(){ Name = "foo" , Address = "Bar" });
//To lookup by key
User user;
if (hash.TryGetValue("22255512282", out user))
{
Console.WriteLine("Found " + user.Name);
}
}
关于c# - 具有 3 个参数的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8367484/