Question

This question already has an answer here:

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top