本人初学者,拿来练习的项目,想要通过遍历哈希表的值来输出信息,请问要如何做?
public string Tname()
{
Console.WriteLine("请输入要查询的姓名:");
string name = Console.ReadLine();
int con = 0;
foreach (string value in tb.ht.Values)
{
if (tb.ht.ContainsValue(name))
{
Console.WriteLine("姓名:{0},电话号码:{1}", tb.ht.Values, tb.ht.Keys);
con++;
}
}
if (con == 0){
Console.WriteLine("查无此人");
}
return name;
}
你不已经做好了吗。还有,这个编辑器是支持markdown的,可以把代码格式化一下
可能我表述不清楚,我是找到键值对了,但是我不知道怎么通过值输出键的信息,我这样的输出只会输出数据类型
@乌合无象: 就像叔这样格式化一下代码才算比较有诚意,如果我没有理解错,你是想要这样:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hash
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person { Name = "Joey", PhoneNumber = "1" };
Person p2 = new Person { Name = "Ross", PhoneNumber = "1" };
Person p3 = new Person { Name = "Monica", PhoneNumber = "1" };
Person p4 = new Person { Name = "Monica", PhoneNumber = "1" };
MyHash<Person> hash = new MyHash<Person>();
hash.Add("Joey", p1);
hash.Add("Ross", p2);
hash.Add("Monica", p3);
hash.Add("Chandler", p4);
var keys = hash.FindKeysByValue(p3);
foreach (var item in keys)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
class Person
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
public override bool Equals(object obj)
{
Person person = obj as Person;
if (person != null)
{
if (person.Name == Name && person.PhoneNumber == PhoneNumber)
{
return true;
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
class MyHash<TValue>
{
private Dictionary<string, TValue> _dic = new Dictionary<string, TValue>();
public void Add(string key, TValue value)
{
if (_dic.Keys.Contains(key))
{
throw new InvalidOperationException("相同键值已存在");
}
else
{
_dic.Add(key, value);
}
}
public List<string> FindKeysByValue(TValue value)
{
List<string> keys = new List<string>();
if (value != null)
{
keys = _dic.Where(d => d.Value.Equals(value)).Select(d => d.Key).ToList();
}
return keys;
}
}
}