由于Lambda Distinct方法默认是按照集合里面的值比较的,所以当集合里面存放的是类的时候,我们一般是按照实体中的某一属性值比较,其实是用默认的Distinct也可以的,自己先定义一个实现了接口IEqualityComparer的类,然后调用Distinct的重载将这个类传递进去,但是这样太麻烦了,而且不能重用 所以参考了一些资料 整了一个程序员最爱的通用的方法
代码如下:
1、先定义比较类实现IEqualityComparer
public class CommonEqualityComparer<T, V> : IEqualityComparer<T> { private Func<T, V> keySelector; private IEqualityComparer<V> comparer; public CommonEqualityComparer(Func<T, V> keySelector, IEqualityComparer<V> comparer) { this.keySelector = keySelector; this.comparer = comparer; } public CommonEqualityComparer(Func<T, V> keySelector) : this(keySelector, EqualityComparer<V>.Default) { } public bool Equals(T x, T y) { return comparer.Equals(keySelector(x), keySelector(y)); } public int GetHashCode(T obj) { return comparer.GetHashCode(keySelector(obj)); } }
2、接下来扩展Distinct 实现针对实体类的属性Distinct的重载方法
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)); } public static IEnumerable<T> Distinct<T, V>(this IEnumerable<T> source, Func<T, V> keySelector, IEqualityComparer<V> comparer) { return source.Distinct(new CommonEqualityComparer<T, V>(keySelector, comparer)); } }
ok完毕,
测试数据:
List<SalesOrder> lists = new List<SalesOrder>() {
new SalesOrder(){SalesOrderNo="aaa"},
new SalesOrder(){SalesOrderNo="bbb"},
new SalesOrder(){SalesOrderNo="aaa"},
new SalesOrder()
};
var item= lists.Distinct(m => m.SalesOrderNo);
完结!thank for you
时间: 2024-10-17 02:31:09