c# – 具有3个参数的Hashtable

前端之家收集整理的这篇文章主要介绍了c# – 具有3个参数的Hashtable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用三个参数创建hashTable?我想使用hashTable和字典存储电话号码,姓名和地址.电话号码作为密钥,名称,地址作为其值.但我只能输入两个数据,电话号码和姓名.如何在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());  
    }
}

解决方法

将所有用户数据放入一个类:
public class User
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
}

然后处理如下:

Dictionary<string,User> reverseLookUp = new Dictionary<string,User>();
User user;

// Fill dictionary
user = new User { Name = "John",Address = "Baker Street",PhoneNumber = "012345" };
reverseLookUp.Add(user.PhoneNumber,user);
user = new User { Name = "Sue",Address = "Wall Street",PhoneNumber = "333777" };
reverseLookUp.Add(user.PhoneNumber,user);

// Search a user
string phoneNumber = "012345";
if (reverseLookUp.TryGetValue(phoneNumber,out user)) {
    Console.WriteLine("{0},{1},phone {2}",user.Name,user.Address,user.PhoneNumber);
} else {
    Console.WriteLine("User with phone number {0} not found!",phoneNumber);
}

// List all users
foreach (User u in reverseLookUp.Values) {
    Console.WriteLine("{0},u.Name,u.Address,u.PhoneNumber);
}

您还可以为此目的创建专用字典:

public class PhoneDict : Dictionary<string,User>
{
    public void Add(User user)
    {
        Add(user.PhoneNumber,user);
    }
}

然后按如下方式添加用户

PhoneDict phoneDict = new PhoneDict();
User user;

// Fill dictionary
user = new User { Name = "John",PhoneNumber = "012345" };
phoneDict.Add(user);
user = new User { Name = "Sue",PhoneNumber = "333777" };
phoneDict.Add(user);
原文链接:https://www.f2er.com/csharp/244117.html

猜你在找的C#相关文章