GetHashCode的与列表对象的类 [英] GetHashCode for a Class with a List Object

查看:123
本文介绍了GetHashCode的与列表对象的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个类:

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.

现在的问题是如何落实的GetHashCode()

The issue now is how to implement the GetHashCode()?

我试过 Edges.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.

推荐答案

您可以这样做:

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



这是简单的,但应该是一致的。

It is simple, but should consistent.

这篇关于GetHashCode的与列表对象的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆