导航

重写类的Equals以及重写Linq下的Distinct方法

Posted on 2014-02-26 16:21  杨彬Allen  阅读(1246)  评论(0编辑  收藏  举报

当自定义一个类的时候,如果需要用到对比的功能,可以自己重写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

 

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();
        }
    }

    public class MarketComparer : IEqualityComparer<Market>
    {
        public bool Equals(Market x, Market y)
        {
            return x.Name == y.Name && x.RegionName == y.RegionName;
        }

        public int GetHashCode(Market obj)
        {
            return obj.Name.GetHashCode() ^ obj.RegionName.GetHashCode();
        }
    }
}
重写Linq下的Distinct方法

 

var xx = lstMarkets.Distinct<Market>(new MarketComparer()).ToList();
Linq下的Distinct调用