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