我来到这个站点在 Dictionary 中搜索对象比较,并且我知道重写 GetHashCode 和 Equals 是在 C# 中进行对象比较的必要条件。这是我一直在尝试解决的一段代码,使用 FOREACH 迭代方法。但是由于性能问题,我的老板说不使用任何迭代(可能使用 containskey 或 containsvalue 方法)也可以这样做。非常欢迎任何帮助..
public class employee
{
public string empname { get; set; }
public string location { get; set; }
public double kinid { get; set; }
public double managerKin { get; set; }
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class manager
{
public string managername { get; set; }
public double kinid { get; set; }
public override int GetHashCode()
{
return 17 * managername.GetHashCode() + kinid.GetHashCode();
}
}
public class program
{
public static void Main()
{
employee emp = new employee();
employee emp2 = new employee();
manager mng = new manager();
manager mng2 = new manager();
emp.empname = "Deepak";
emp.location = "Pune";
emp.kinid = 36885;
emp.managerKin = 007;
emp2.empname = "Astha";
emp2.location = "Pune";
emp2.kinid = 30000;
emp2.managerKin = 007;
mng.kinid = 007;
mng.managername = "Gaurav";
mng2.kinid = 001;
mng2.managername = "Surya";
Dictionary<employee, manager> relations = new Dictionary<employee, manager>();
relations.Add(emp, mng);
relations.Add(emp2, mng2);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("The Manager details are :");
foreach (var element in relations)
Console.WriteLine(" \n KINID : {0} \n Manager'sName : {1}",element.Value.kinid, element.Value.managername);
Console.WriteLine("Enter the details of the manager..");
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("\nManager's Kin : ");
double mkin = Convert.ToDouble(Console.ReadLine());
Console.Write("Manager's Name : ");
string mname = Console.ReadLine();
manager mng1 = new manager();
mng1.kinid = mkin;
mng1.managername = mname;
int hashvalue = 17 * mname.GetHashCode() + mkin.GetHashCode();
#region BY USING FOREACH LOOP
int i = 0;
foreach (var element in relations)
{
if (element.Value.GetHashCode() == hashvalue)
{
i += 1;
if (i == 1)
{
Console.WriteLine("The Following employees report to the Manager : {0}", mname);
}
Console.WriteLine(element.Key.empname + " " + element.Key.kinid + " " + element.Key.location + " " + element.Key.managerKin);
}
}
if (i == 0)
{
Console.WriteLine("sorry the manager's details you entered \"{0}\" \"{1}\" does not exist in our database..", mng1.managername, mng1.kinid);
}
#endregion
Console.ReadLine();
}
}