Search code examples
c#equalityiequalitycomparer

Why IEqualityComparer doesn't work as expected?


Why EqualityComparer MyEqComp doesn't work? It should left in arr only 2 elements with equal Values - myDic["1"]and myDic["3"] with Value="456". But instead it consists of myDic["1"] and myDic["2"] but their Values are not equal. Function GetHashCode returns the same hash code for 1st and 3rd elements!

public class Program
    {
        public static Dictionary<string,string> myDic = new Dictionary<string,string>();
        public static void Main()
        {
            myDic.Add("1","456");
            myDic.Add("2","567");
            myDic.Add("3","456");
            var arr=myDic.Distinct(new MyEqComp());
            foreach (var n in arr)
            {
                Console.WriteLine("key="+n.Key+",value="+n.Value+"\n");
            }
        
        }
        class MyEqComp:IEqualityComparer<KeyValuePair<string,string>>{
            public bool Equals(KeyValuePair<string,string> pair1, KeyValuePair<string,string> pair2){
                Console.WriteLine("pair1="+pair1+",pair2="+pair2);
                return pair1.Value == pair2.Value;
            }
            public int GetHashCode(KeyValuePair<string,string> pair){
                var code = pair.Value.GetHashCode();
                Console.WriteLine("code="+code);
                return code;
            }
        }
        
    }

And the output

code=-121858068
key=1,value=456

code=437991364
key=2,value=567

code=-121858068
pair1=[1, 456],pair2=[3, 456]

Solution

  • Answer: Code is correct and works as expected.