I'm trying to compare custom type in two List<T>
and use the Intersect
/ Except
method. The equality is determined by three fields of this type. The equality is based on more than the ordinary condition (all fields contains the same data). I implemented of course the IEqualityComparer<T>
. My problem is that the GetHashCode()
method return not equal once the hashCode is not the same and this does not help me since this is not true in my case.
Is there any way to compare two custom object when equality is based on more than one condition so I can use intersect/except/distinct etc...?
Here is my code :
public bool Equals(ComparableObject x, ComparableObject y)
{
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
if (Object.ReferenceEquals(x, y))
return true;
if (x.Var1.Equals(y.Var1) && x.Var3.Equals(y.Var3) && !x.Var2.Equals(y.Var2))
return false;
if (x.Var1.Equals(y.Var1) && !x.Var3.Equals(y.Var3) && !x.Var2.Equals(y.Var2))
return true;
if (!x.Var1.Equals(y.Var1) && x.Var3.Equals(y.Var3) && !x.Var2.Equals(y.Var2))
return false;
if (!x.Var1.Equals(y.Var1) && x.Var3.Equals(y.Var3) && x.Var2.Equals(y.Var2))
return true;
if (x.Var1.Equals(y.Var1) && !x.Var3.Equals(y.Var3) && x.Var2.Equals(y.Var2))
return false;
if (!x.Var1.Equals(y.Var1) && !x.Var3.Equals(y.Var3) && x.Var2.Equals(y.Var2))
return false;
if (!x.Var1.Equals(y.Var1) && !x.Var3.Equals(y.Var3) && !x.Var2.Equals(y.Var2))
return false;
return x.Var1.Equals(y.Var1) && x.Var1.Equals(y.Var1) && x.Var3.Equals(y.Var3);
}
public int GetHashCode(ComparableObject x)
{
return obj.Var1.GetHashCode() ^ obj.Var2.GetHashCode()^ obj.Var3.GetHashCode()
}