簡體   English   中英

字典C中的GetHashCode和Equals實現#

[英]GetHashCode and Equals implementation in Dictionary C#

我來到這個網站,在Dictionary中搜索對象比較,我開始知道重寫GetHashCode和Equals是在C#中進行對象比較的必要條件。 這是我嘗試使用FOREACH迭代方法解決的一段代碼。 但是由於性能問題,我的Boss說在不使用任何迭代(可能使用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();
        }

    }

為了使用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

要在字典中搜索元素,您可以使用ContainsKey,ContainsValue方法或只編寫LINQ查詢

var dict = (from pair in relations
where pair.Value.Equals(mng1)
select pair).ToDictionary<employee,manager>();

Dictionary.ContainsKey(employee)在這里沒有幫助,因為員工是“未知”值,而Contains將無濟於事,因為它需要一個KeyValuePair<employee,manager>和......再次......沒有員工知道。 ContainsValue(manager)將無法幫助,因為它不返回任何鍵因為它不是鍵,它是O(n)操作,而不是像ContainsKey這樣的O(1)

使用當前結構唯一的方法是使用某種形式的循環,雖然我會這樣寫:

// 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==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對象被用作新詞典的鍵。)

至於哪個是“更好” - 嗯,這取決於。 例如,創建反向查找僅使用一次是愚蠢的。 在出現性能問題之前沒有性能問題:編寫干凈的代碼和配置文件。

快樂的編碼。

為了能夠比較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);

我相信你的最終回復中有一個錯誤。

這條線

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

可能應該是

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

這樣您就可以比較此對象和其他對象的哈希碼。 正如您在回復中所寫的那樣,您似乎正在將另一個對象與自身進行比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM