tags:

views:

194

answers:

1

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.

+5  A: 

You could do something like:

override int GetHashCode()
{
  return Edges.Distinct().OrderBy(x => x).Aggregate(0, (x,y) =>x.GetHashCode() ^ y.GetHashCode());
}

It is simple, but should consistent. But you need to care of duplicates and the ordering of elements (i tried to eliminate those, but is not 100% sure).

leppie
+1 I don't see in which case it may fail for two equal lists, can you elaborate?
Groo
{1,2,3} vs {3,3,2,2,1,1}
leppie