当自定义一个类的时候,如果需要用到对比的功能,可以自己重写Equals方法,最整洁的方法是重写GetHashCode()方法。

但是,这个方法只适用于对象自身的对比(如if(a==b))以及字典下的Contains(如dicTest.Contains<T>(a)),在Linq下的Distinct下无效。

Linq下的Distinct需要我们再写一个继承IEqualityComparer的类,分别如下

using System.Collections.Generic;

namespace ServiceEngine.Model
{
    public class Market
    {
        /// <summary>
        /// 区域名称
        /// </summary>
        public string RegionName { get; set; }
        /// <summary>
        /// 市场名称
        /// </summary>
        public string Name { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
            if (obj.GetType() != this.GetType())
                return false;

            Market m = obj as Market;
            return m.Name == this.Name && m.RegionName == this.RegionName;
        }

        public override int GetHashCode()
        {
            return this.Name.GetHashCode() ^ this.RegionName.GetHashCode();
        }
    }
}
重写类的Equals

相关文章:

  • 2021-11-04
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
猜你喜欢
  • 2021-05-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案