Linq下的distinct()比SQLServer下的distinct更强大,更自由,呵呵

大家好,今天调点时间来说一下LINQ里的distinct(),以及解决过滤重复记录的方法

准备数据:先来个实体类,自己为它赋值,然后用 linq to object对象它进行distinct的操作

public abstract class BaseEntity
   {
       public BaseEntity() : this(0) { }

       public BaseEntity(long id)
       {
           ID = id;
       }

       public long ID { get; private set; }
   }
   class People : BaseEntity
   {
       public string UserName { get; set; }
       public string Email { get; set; }
       public int Age { get; set; }
   }
        #region linq to object 
         List<People> peopleList = new List<People>();
            peopleList.Add(new People { UserName = "zzl", Email = "1" });
            peopleList.Add(new People { UserName = "zzl", Email = "1" });
            peopleList.Add(new People { UserName = "lr", Email = "2" });
            peopleList.Add(new People { UserName = "lr", Email = "2" });

            Console.WriteLine("用扩展方法可以过滤某个字段,然后把当前实体输出");
            peopleList.DistinctBy(i => new { i.UserName }).ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email));
            Console.WriteLine("默认方法,集合中有多个字段,当所有字段发生重复时,distinct生效,这与SQLSERVER相同");
            peopleList.Select(i => new { UserName = i.UserName, Email = i.Email }).OrderByDescending(k => k.Email).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName + i.Email));
            Console.WriteLine("集合中有一个字段,将这个字段重复的过滤,并输出这个字段");
            peopleList.Select(i => new { i.UserName }).Distinct().ToList().ForEach(i => Console.WriteLine(i.UserName));

            #endregion
image 

下面我们来看一下linq to sql的测试情况,看代码:

        #region 对linq to sql进行Ddistinct()
         DataClasses1DataContext db = new DataClasses1DataContext();
            Console.WriteLine("对单个字段可以实现");
            db.Customer.Select(i => new { i.Name }).Distinct().ToList().ForEach(i => Console.WriteLine(i.Name));
            Console.WriteLine("直接对原-数据集中多个字段进行过滤");
            db.Customer.ToList().Select(i => new { Name = i.Name, Email = i.Email }).Distinct().ToList().ForEach(i =>
            {
                Console.WriteLine(i.Name + i.Email);
            });
            Console.WriteLine("将linq to sql对象赋给别一个实体对象时出现了不能过滤的问题");
            List<Customermodel> entity = new List<Customermodel>();
            db.Customer.ToList().Select(i => new { Name = i.Name, Email = i.Email }).ToList().ForEach(i =>
            {
                entity.Add(new Customermodel { Name = i.Name, Email = i.Email });
            });
            entity.Distinct().ToList().ForEach(i => Console.WriteLine(i.Name + i.Email));
            Console.WriteLine("使用distinct扩展方法进行过滤,没有问题");
            entity.DistinctBy(j => new { j.Name }).ToList().ForEach(i => Console.WriteLine(i.Name + i.Email));
            #endregion
测试结果:
image 
 

最后,贡献出DistinctBy这个IEnumerable的扩展方法:

image

原文地址:https://www.cnblogs.com/lori/p/2373199.html