c#比较器辅助类
/// <summary> /// 比较器帮助类 /// 创建人:苏本东 /// 创建时间:2019-11-5 11:52:29 /// </summary> public class ComparerHelper<T> : IEqualityComparer<T> { private readonly Func<T, T, bool> _func; /// <summary> /// 构造方法 /// </summary> /// <param name="func"></param> public ComparerHelper(Func<T, T, bool> func) { this._func = func; } /// <summary> /// 比较是否相等 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public bool Equals(T x, T y) { return this._func(x, y); } /// <summary> /// 返回哈希代码 /// </summary> /// <param name="obj"></param> /// <returns></returns> public int GetHashCode(T obj) { //说明:此场景,不管obj的hashcode还是obj.id的hashcode都不会相同 //而如果hashcode不相同,就不会走到equals方法 //所以我们这里必须返回相同的hashcode,只有这样,equals方法才有机会被执行 return 1; } }
比较的条件是一个匿名函数,通过构造方法传入。仔细看标红的文字。参考:https://www.cnblogs.com/mirageJ/p/8950842.html
随后又封装了一个类进行调用
/// <summary> /// 检查excel数据是否重复的帮助类 /// </summary> public class CheckExcelDuplicateHelper { /// <summary> /// 检查excel重复数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">数据集合</param> /// <param name="func">条件</param> /// <returns></returns> public static Response<string> Check<T>(List<T> list, Func<T, T, bool> func) where T : class { var result = new Response<string>(); var oldAmount = list.Count; list = list.Distinct(new ComparerHelper<T>(func)).ToList(); var newAmount = list.Count; if (oldAmount > newAmount) { result.Code = 500; result.Message = $"不允许有重复数据;"; } return result; } }
最终调用如下:
//检查Excel重复数据 result = CheckExcelDuplicateHelper.Check(response.Result, (x, y) => { return x.FactoryId == y.FactoryId && x.WorkshopId == y.WorkshopId && x.LineNameCN == y.LineNameCN; });
另外,在学习的时候,发现Func<T, bool>和Express<Func<T, bool>>是有区别的,特别是在查询数据库时,Func<T, bool>是从所有结果中查询,Express<Func<T, bool>>则是根据条件查询。
参考:https://www.cnblogs.com/walkerwang/archive/2013/03/26/2983153.html