Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode for a class with a list object [duplicate]

Tags:

c#

gethashcode

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.

like image 493
Graviton Avatar asked Oct 27 '09 11:10

Graviton


People also ask

When should we override the GetHashCode () method?

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.

What is GetHashCode method?

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.

Why do we need GetHashCode C#?

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.

Is GetHashCode unique C#?

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.


1 Answers

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.

like image 196
leppie Avatar answered Sep 23 '22 19:09

leppie