C# List去重的三種方法(轉)


三種去重的方法

1、List中的元素實現IEquatabe接口,並提供Equals方法和GetHashCode方法。

2、使用表達式

[csharp]  view plain copy
 
  1. users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i)  
 
         

去重,這條語句返回結果只保留users這個List中重復的元素的第一個(name相等認為重復)。

3、使用循環,判斷每個元素是否重復

 

 

[csharp]  view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace NonDuplicateList  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             List<User> users = new List<User>();  
  12.             users.Add(new User("張三", "永豐路299號"));  
  13.             users.Add(new User("張三", "上地西路8號"));//重復項,去重后將刪掉  
  14.             users.Add(new User("李四", "海鷹路甲一號"));  
  15.   
  16.             List<User> nonDuplicateList1 = users.Distinct().ToList();//通過User類的Equals實現去重  
  17.             List<User> nonDuplicateList2 = users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i).ToList();//Lambda表達式去重  
  18.             List<User> nonDuplicateList3 = new List<User>();//通過循環方式去重  
  19.             foreach(User user in users)  
  20.             {  
  21.                 if(nonDuplicateList3.Exists(x=>x.name==user.name) == false)  
  22.                 {  
  23.                     nonDuplicateList3.Add(user);  
  24.                 }  
  25.             }  
  26.   
  27.             foreach(List<User> list in new Object[]{nonDuplicateList1,nonDuplicateList2,nonDuplicateList3})//打印出三個List的元素  
  28.             {  
  29.                 Console.Write("nonDuplicateList:\r\n");  
  30.                 foreach(User u in list)  
  31.                 {  
  32.                     Console.WriteLine("\t" + u.ToString());  
  33.                 }  
  34.             }  
  35.             Console.Read();  
  36.         }  
  37.     }  
  38.   
  39.     class User:IEquatable<User>//繼承IEquatable接口,實現Equals方法。List就可以使用Distinct去重  
  40.     {  
  41.         public string name { get; set; }  
  42.         string address;  
  43.   
  44.         public User(string _name, string _address)  
  45.         {  
  46.             name = _name;  
  47.             address = _address;  
  48.         }  
  49.   
  50.         public override string ToString()  
  51.         {  
  52.             return string.Format("name:{0},\taddress:{1}", name, address);  
  53.         }  
  54.   
  55.         public bool Equals(User other)  
  56.         {  
  57.             return this.name == other.name;  
  58.         }  
  59.         public override int GetHashCode()  
  60.         {  
  61.             return name.GetHashCode();  
  62.         }  
  63.     }  
  64. }  

 


免責聲明!

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



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