c# - Is it possible to write a hash code function for an comparer that matches many-to-many? -
can write hash code function following comparer logic?
two instances of my equal if @ least 2 properites (a, b, c) match.
the equals part simple, i'm stumped on hash code part, , part of me thinking might not possible.
class myothercomparer : iequalitycomparer<my> { public bool equals(my x, y) { if (object.referenceequals(x, y)) return true; if (object.referenceequals(x, null) || object.referenceequals(y, null)) return false; int matches = 0; if(x.a == y.a) matches++; if(x.b == y.b) matches++; if(x.c == y.c) matches++; // match on 2 out of 3 return (matches > 1) } // if equals() returns true pair of objects // gethashcode() must return same value these objects. public int gethashcode(my x) { // ??? } } update: in addition correct answer reed copsey, important point general usefulness of fuzzy comparer stated ethan brown - please see answer full understanding of underlies question/answer.
yes, it's possible. simplest implementation return constant.
public int gethashcode(my x) { return 0; } the gethashcode documentation states:
implementations required ensure if equals method returns true 2 objects x , y, value returned gethashcode method x must equal value returned y.
however, free return same hash code 2 objects not equal, well.
that being said, potentially cause algorithms perform poorly, you'll lots of hash collisions. however, given nature of odd/unique equality check, may required.
note going problematic in case. given logic, it's possible have 3 objects, comparer.equals(foo, bar)==true , comparer.equals(foo, baz)==true comparer.equals(baz, bar)==false. problematic in many cases iequalitycomparer<t> used.
Comments
Post a Comment