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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM