有时候我们需要从List<entity>数据源中去重,得需要实现IEqualityComparer接口和重写Equals以及GetHashCode,但是问题来了,如果entity数量很多,得一个一个的去写,有点麻烦,所以这里介绍泛型通用。
先看实体类
再看数据源(显然Id重复有1和2)
调用
?达到目的。下面直接上源码
public class ClassAdapter<T> : IEqualityComparer<T> where T : new()
{
private string _propertyName = string.Empty;
private PropertyInfo[] propertyInfos=null;
private BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance;
public ClassAdapter(string propertyName)
{
_propertyName = propertyName;
}
public bool Equals(T? x, T? y)
{
if (Object.ReferenceEquals(x, null))
return false;
if (Object.ReferenceEquals(y, null))
return false;
if (x.GetType() != y.GetType())
return false;
if (Object.ReferenceEquals(x, y))
return true;
var x_propertyInfo = GetPropertyInfo(x);
var y_propertyInfo = GetPropertyInfo(y);
if (x_propertyInfo == null || y_propertyInfo == null)
return false;
return x_propertyInfo.GetValue(x).Equals(y_propertyInfo.GetValue(y));
}
public int GetHashCode([DisallowNull] T obj)
{
return GetPropertyInfo(obj)?.GetHashCode()??0;
}
private PropertyInfo GetPropertyInfo(T obj)
{
if(propertyInfos == null)
{
var type = obj.GetType();
propertyInfos = type.GetProperties();
}
return propertyInfos.Where(t => _propertyName.Equals(t.Name)).FirstOrDefault();
}
}
|