lambda List实现某列去重的解决方案采用扩展方法

时间:2021-08-03 14:52:51

public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
{
private Func<T, V> keySelector;

public CommonEqualityComparer(Func<T, V> keySelector)
{
this.keySelector = keySelector;
}

public bool Equals(T x, T y)
{
return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
}

public int GetHashCode(T obj)
{
return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
}
}
/// <summary>
/// List去重复
/// </summary>
public static class DistinctExtensions
{
public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector)
{
return source.Distinct(new CommonEqualityComparer<T, V>(keySelector));
}
}

调用示例:

result = result.Distinct(p => p.groupid).OrderByDescending(m=>m.addtime).ToList();