I have such a class:
public class Cycle
{
public List<int> Edges
{
get;
private set;
}
public override bool Equals(object obj)
{
Cycle cycle = (Cycle)obj;
var list1 = cycle.Edges;
var list2 = Edges;
var same = list1.Except(list2).Count() == 0 &&
list2.Except(list1).Count() == 0;
return same;
}
public override int GetHashCode()
{
// return Edges.GetHashCode();
}
}
As you can see, if two Edge
Lists are the same, then I deem the Cycles
as the same.
The issue now is how to implement the GetHashCode()
?
I tried Edges.GetHashCode()
, but the problem is that two List<Cycle>
, with the same Cycle
object but different orders, will be deemed different, even though they should be the same.
It's my understanding that the original GetHashCode() returns the memory address of the object, so it's essential to override it if you wish to compare two different objects.
GetHashCode method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes.
GetHashCode() Method with Examples. This method is used to return the hash code for this instance. A hash code is a numeric value which is used to insert and identify an object in a hash-based collection. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.
NO! A hash code is not an id, and it doesn't return a unique value. This is kind of obvious, when you think about it: GetHashCode returns an Int32 , which has “only” about 4.2 billion possible values, and there's potentially an infinity of different objects, so some of them are bound to have the same hash code.
You could do something like:
override int GetHashCode()
{
return Edges.Distinct().Aggregate(0, (x,y) =>x.GetHashCode() ^ y.GetHashCode());
}
It is simple, but should consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With