GetHashCode for a Class with a List Object [duplicate]

南楼画角 提交于 2019-11-29 20:53:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1630183/gethashcode-for-a-class-with-a-list-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!