Linq distinct去重方法之一

var result = query.Distinct().ToList();

List<DeliveryOrderViewModel> dov = result.GroupBy( p => new {p.SAP_DeliveryOrderID}).Select( g =>g.First()).ToList();

return dov;

一、使用Distinct()扩展方法去重
 
实例:根据Id去重
错误的方式
 
    List<Product> products = new List<Product>()
    {
        new Product(){ Id="1", Name="n1"},
        new Product(){ Id="1", Name="n2"},
        new Product(){ Id="2", Name="n1"},
        new Product(){ Id="2", Name="n2"},
    };

    var distinctProduct = products.Distinct();


返回4条数据,因为Distinct 默认比较的是Product对象的引用
 
正确的方式
新建类ProductIdComparer,继承 IEqualityComparer<Product>,实现Equals方法
 
C# 代码   复制


public class ProductIdComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        if (x == null)
            return y == null;
        return x.Id == y.Id;
    }


    public int GetHashCode(Product obj)
    {
        if (obj == null)
            return 0;
        return obj.Id.GetHashCode();
    }
}
 
使用的时候,只需要


var distinctProduct = allProduct.Distinct(new ProductIdComparer());
 
备注:现在假设我们要 按照 Name来筛选重复呢?则需要再添加一个类ProductNameComparer.
 
二、使用GroupBy方式去重
对需要Distinct的字段进行分组,取组内的第一条记录这样结果就是Distinct的数据了。
例如
 
List<Product> distinctProduct = allProduct
  .GroupBy(p => new {p.Id, p.Name} )
  .Select(g => g.First())
  .ToList();

 
三、通过自定义扩展方法DistinctBy实现去重
 
 
C# 代码   复制

public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
   {
        if (seenKeys.Add(keySelector(element)))

        {
            yield return element;
        }
    }
}


方法的使用
1、针对ID,和Name进行Distinct
var query = allProduct.DistinctBy(p => new { p.Id, p.Name });
2、仅仅针对ID进行distinct:
var query = allProduct.DistinctBy(p => p.Id);

猜你喜欢

转载自blog.csdn.net/xwnxwn/article/details/89602105