0

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]
NoImagination
  • 178
  • 1
  • 8
  • 6
    I think you've misread the description of what `Distinct` is meant to do - it's meant to give *distinct* values, effectively eliminating any duplicates. It sounds like you're expecting it to *return* the duplicates. That output looks fine to me. – Jon Skeet Sep 27 '22 at 20:22
  • @Jon Skeet, you are right! I am tired, I need to rest :D – NoImagination Sep 27 '22 at 20:28
  • Are you sure == works for your values which seems to be string ? – pirela Sep 27 '22 at 20:31
  • 1
    I think your own extensive logging confused you. The last keyvaluepair is not returned (correctly), because it has the same value the first. – Tim Schmelter Sep 27 '22 at 20:32
  • @pirela, it doesn't matter in my case now, its just for testing purposes but yes, strings in this case can be compared with ==. – NoImagination Sep 27 '22 at 20:35
  • 1
    NoImagination you can ignore @pirela comment - they likely believe this is Java question (where you can't use == to compare strings). – Alexei Levenkov Sep 27 '22 at 20:37

1 Answers1

0

Answer: Code is correct and works as expected.

NoImagination
  • 178
  • 1
  • 8