c#比较器辅助类
2021-05-16 20:28
标签:expr readonly ESS 重复数据 cat 匿名 通过 count div 比较的条件是一个匿名函数,通过构造方法传入。仔细看标红的文字。参考:https://www.cnblogs.com/mirageJ/p/8950842.html 随后又封装了一个类进行调用 最终调用如下: 另外,在学习的时候,发现Func 参考:https://www.cnblogs.com/walkerwang/archive/2013/03/26/2983153.html c#比较器辅助类 标签:expr readonly ESS 重复数据 cat 匿名 通过 count div 原文地址:https://www.cnblogs.com/subendong/p/11797570.html /// summary>
/// 比较器帮助类
/// 创建人:苏本东
/// 创建时间:2019-11-5 11:52:29
/// summary>
public class ComparerHelperT> : IEqualityComparerT>
{
private readonly FuncT, T, bool> _func;
/// summary>
/// 构造方法
/// summary>
/// param name="func">param>
public ComparerHelper(FuncT, 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;
}
}
/// 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 Responsestring> CheckT>(ListT> list, FuncT, T, bool> func) where T : class
{
var result = new Responsestring>();
var oldAmount = list.Count;
list = list.Distinct(new ComparerHelperT>(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;
});