public class Compare<T, C> : IEqualityComparer<T>
{
private Func<T, C> _getField;
public Compare(Func<T, C> getField)
{
_getField = getField;
}
public bool Equals(T x, T y)
{
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<C>.Default.GetHashCode(_getField(obj));
}
}
public static class DistinctExtension
{
/// <summary>
/// 自定义 Distinct扩展方法
/// </summary>
/// <typeparam name="T">要去重的对象类</typeparam>
/// <typeparam name="C">自定义去重的字段类型</typeparam>
/// <param name="source">要去重的对象</param>
/// <param name="getField">获取自定义去重字段的委托</param>
/// <returns></returns>
public static IEnumerable<T> DistinctByField<T, C>(this IEnumerable<T> source, Func<T, C> getField)
{
return source.Distinct(new Compare<T, C>(getField));
}
}
Distinct 扩展方法(按字段去重)
最新推荐文章于 2024-04-16 14:44:33 发布