when passing EqualityComparer as last parameter to Linq Join method it is not using Equals method of it, it for some reason is using GetHashCode to compare items.
Is it possible to make it use Equals instead?
var ss = new string[] { "aa", "bb", "cc" };
var zz = new string[] { "aa", "zz", "cc" };
var res = ss
.Join(zz,
o => o,
i => i,
(i, o) => i + o,
new GenericEqualityComparer<String>((x,y) => x == y))
.ToList();
When an
IEqualityComparer<T>compares to objects, it first compares their hashcodes. Only if they are equal theEqualsmethod is used to refine the comparison. So in your case it should at least hitEqualstwice.To demonstrate what an EqualityComparer does I made a little code snippet in Linqpad:
So strings are equal if their first two characters are equal. The output is:
And the resulting list:
You see that first the second list is compared (I’m not sure why, by the way, maybe the hashcodes are cached) and then the pairs.
So when your
GenericEqualityComparernever hitsEqualsit somehow always generates a unique hashcode, which I think should be a bug. If it not always usesEquals, here is the explanation. And if you want a comparer to always useEqualsyou should make it always return an identical hashcode (which is inefficient, of course).