有时候我们需要从List<entity>数据源中去重,得需要实现IEqualityComparer接口和重写Equals以及GetHashCode,但是问题来了,如果entity数量很多,得一个一个的去写,有点麻烦,所以这里介绍泛型通用。
先看特性
再看实体类
再看数据源
调用
达到目的。下面直接上源码
public class ClassAdapter<T> : IEqualityComparer<T> where T : new()
{
private List<PropertyInfo> propertyInfos = null;
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_propertyInfos = GetPropertyInfos(x);
var y_propertyInfos = GetPropertyInfos(y);
bool status = true;
for(int i=0;i< x_propertyInfos.Count;i++)
{
var x_value = x_propertyInfos[i].GetValue(x);
var y_value = y_propertyInfos[i].GetValue(y);
var falge = x_value.Equals(y_value);
status = status && falge;
if (!status)
break;
}
return status;
}
public int GetHashCode([DisallowNull] T obj)
{
if (Object.ReferenceEquals(obj, null))
return 0;
int code = 0;
foreach(var item in GetPropertyInfos(obj))
{
code ^= item.GetHashCode();
}
return code;
}
private List<PropertyInfo> GetPropertyInfos(T obj)
{
if (propertyInfos == null)
{
var type = obj.GetType();
var bute = typeof(AdapterAttribute);
propertyInfos = type.GetProperties().Where(t => t.GetCustomAttributes(bute, false).Length > 0).ToList();
}
return propertyInfos;
}
}
上面是用泛型+反射+特性达到目的,下面介绍Linq去重
var data = list.GroupBy(t => new { t.Id, t.Head }).Select(x => x.FirstOrDefault()).ToList();