3

我来到这个站点在 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();
        }

    }
4

5 回答 5

3

为了使用 ContainsKey 或 ContainsValue 关键字在字典中搜索对象,编译器使用两个隐式函数,即 GetHashCode() 和 Equals()。所以当我们有一个对象进行比较时,我们需要重写这两个方法!

这是代码

#region USING DICTIONARY TO STORE CLASS OBJECTS (check employee existence and print manager's name)
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) // ANY OF THE TWO EQUALS METHOD WORKS.
    //{
    //    employee otheremployee;
    //    otheremployee = (employee)obj;
    //    return (otheremployee.kinid == this.kinid && otheremployee.location == this.location && otheremployee.empname == this.empname && otheremployee.managerKin == this.managerKin);

    //}
    public override bool Equals(object obj)   //When Running this entire code, put a break-point on both the Equals() and GetHashCode() methods, and see the execution flow.
    {
        employee otheremployee;
        otheremployee = (employee)obj;
        return (obj.GetHashCode() == otheremployee.GetHashCode());

    }
    public override int GetHashCode()    //When Running this entire code, put a break-point on both the Equals() and GetHashCode() methods, and see the execution flow.
    {
        //int temp = base.GetHashCode(); // DONT USE THIS
        //return base.GetHashCode();
        int temp = empname.GetHashCode() + location.GetHashCode() + kinid.GetHashCode() + managerKin.GetHashCode();
        return temp;
    }
}

public class manager
{
    public string managername { get; set; }
    public double kinid { get; set; }


   
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
}
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 = 001;

        mng.kinid = 007;
        mng.managername = "Gaurav";
        mng2.kinid = 001;
        mng2.managername = "Surya";

        Dictionary<employee, manager> relations = new Dictionary<employee, manager>();
        relations.Add(emp, mng); // put a BreakPoint here and see the execution flow
        relations.Add(emp2, mng2);// put a BreakPoint here and see the execution flow

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("The Employee details are :");
        foreach (var element in relations)
            Console.WriteLine(" \n Employee Name : {0} \n Location : {1} \n Employee KinId : {2} \n Manager's KinId : {3} ",
                element.Key.empname, element.Key.location, element.Key.kinid, element.Key.managerKin);

        Console.WriteLine("Enter the details of the Employee..");
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.Write("\nEmployee Name : "); string ename = Console.ReadLine();
        Console.Write("Location : "); string elocn = Console.ReadLine();
        Console.Write("Employee KinId : "); double ekinid = Convert.ToDouble(Console.ReadLine());
        Console.Write("Manager's ID : "); double emngr = Convert.ToDouble(Console.ReadLine());
        employee emp1 = new employee();
        emp1.empname = ename;
        emp1.location = elocn;
        emp1.kinid = ekinid;
        emp1.managerKin = emngr;


        int i = 0; // This variable acts as a indicator to find whether the Employee Key exists or not.
        if (relations.ContainsKey(emp1)) //Put a break point here and see the execution flow.
        {
            Console.WriteLine("the Employee : {0} exists..", emp1.empname);
            Console.WriteLine("the Employee reports to the following manager : {0} \n and the Manager's KinId is {1}.", (relations[emp1]).managername, relations[emp1].kinid);
            i = 1;
            Console.ReadLine();
        }

        if (i == 0)
        {
            Console.WriteLine("the details of the employee named {0} does not exist !!", emp1.empname);
            Console.ReadLine();
        }

#endregion
于 2011-12-23T15:21:05.433 回答
1

要在字典中搜索元素,您可以使用 ContainsKey、ContainsValue 方法或只编写 LINQ 查询

var dict = (from pair in relations
where pair.Value.Equals(mng1)
select pair).ToDictionary<employee,manager>();
于 2011-12-23T07:15:48.643 回答
1

为了能够比较 2 个实例的相等性,您应该重写 Equals 方法,并且实现IEquatable<T>. 当您覆盖 Equals 时,您还应该覆盖 GetHashcode(当您将实例放入字典以计算存储桶时使用此代码)。

您不应该使用GetHashcode自己来比较对象的 2 个实例是否相等;相反,您应该使用Equals(或一个EqualityComparer,它也将使用 Equals 方法)。

如果您已经很好地实现了 GetHashCode 和 Equals,那么您可以通过执行以下操作来确定字典是否包含特定实例:

var myDictionary<int, Manager> = new Dictionary<int,Manager>();

myDictionary.ContainsKey (someKey)

或者

var mySet = new HashSet<Manager>();
mySet.Contains(someManagerObject);
于 2011-12-23T07:36:31.567 回答
1

Dictionary.ContainsKey(employee)在这里不会有帮助,因为员工是“未知”值,Contains也不会有帮助,因为它需要一个KeyValuePair<employee,manager>和......再一次......没有员工是已知的。ContainsValue(manager)无济于事,因为它不返回任何键,并且因为它不是键,所以它是一个O(n)操作,而不是一个O(1)like ContainsKey

使用当前结构,唯一的方法是使用某种形式的循环,尽管我会这样写:

// Key is Employee, Value is Manager
// This is O(n)
var theEmployees = relations
  .Where(rel => rel.Value.Equals(theManager))
  .Select(rel => rel.Key);

manager这只有在给出有效的Equals实现后才会起作用。请注意,根本不使用哈希码。(因为不同的对象可能共享相同的哈希码,所以仅比较哈希码并不能替代Equals, or ==, or CompareTo! -- 取决于哪个合适。)

如果会有很多这样的查询,那么可以“反转”初始结构。

// Build a reverse lookup-up
var employeesForManager = relations
  .GroupBy(rel => rel.Value)            // group on Manager
  .ToDictionary(g => g.Key, g => g);    // Key is the group's Manager

// This is O(1), but only valid AFTER employeesForManager is [re-]generated
var theEmployees = employeesForManager[theManager]

这仅在manager具有有效EqualsGetHashCode实施的情况下才有效。(GetHashCode 是必需的,因为manager对象被用作新字典的键。)

至于哪个“更好”——嗯,这取决于。例如,创建反向查找只使用一次是很愚蠢的。直到出现性能问题才出现性能问题:编写干净的代码和配置文件。

快乐编码。

于 2011-12-23T07:26:48.383 回答
0

我相信您的最终回复中有错误。

线

return (obj.GetHashCode() == otheremployee.GetHashCode());

大概应该是

return (this.GetHashCode() == otheremployee.GetHashCode());

这样你就可以比较这个对象和另一个对象的哈希码。正如您在回复中所写的那样,您似乎正在将另一个对象与自身进行比较。

于 2013-05-09T17:30:37.447 回答