public static class LinqExtensions { public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, System.Func<T, TKey> property) { GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T, TKey>(property); return items.Distinct(comparer); } } public class GeneralPropertyComparer<T, TKey> : IEqualityComparer<T> { private System.Func<T, TKey> expr { get; set; } public GeneralPropertyComparer(System.Func<T, TKey> expr) { this.expr = expr; } public bool Equals(T left, T right) { var leftProp = expr.Invoke(left); var rightProp = expr.Invoke(right); if (leftProp == null && rightProp == null) return true; else if (leftProp == null ^ rightProp == null) return false; else return leftProp.Equals(rightProp); } public int GetHashCode(T obj) { var prop = expr.Invoke(obj); return (prop == null) ? 0 : prop.GetHashCode(); } }
自带的Distinct能做的事比较简单,对比集合中的Object的Hash值来去重
很多时候我们需要的是根据Object中的某个字段值来做去重,比如Student.Name
那么自带的Distinct就要自己实现一个Comparer了
找了很多资料,发现有前人种下了这棵树,分享出来。
Usage:{Linq代码}.DistinctBy(Student.Name).ToList();