Three ways to de-weigh
1. The elements in the list implement the Iequatabe interface and provide the Equals method and the GetHashCode method.
2. Using expressions
Users. Where ((x,i) =>users. FindIndex (Z=>z.name = = x.name) = = i)
Go heavy, this statement returns the result only the first of the duplicate elements in the list (name equals is considered duplicates).
3. Use loops to determine if each element repeats
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; namespaceNonduplicatelist {classProgram {Static voidMain (string[] args) {List<User> users =NewList<user>(); Users. ADD (NewUser ("Zhang San","No. No. 299 Yongfeng Road")); Users. ADD (NewUser ("Zhang San","No. 8th, Shang Xi Road"));//duplicates, which will be deleted when the weight is removed.Users. ADD (NewUser ("John Doe","Sea Eagle Road Armour one")); List<User> nonDuplicateList1 = users. Distinct (). ToList ();//using the equals of the user class to achieve the weightList<user> nonDuplicateList2 = users. Where ((x,i) =>users. FindIndex (Z=>z.name = = x.name) = = i). ToList ();//lambda expression de-weightList<user> NonDuplicateList3 =NewList<user> ();//to weigh in a circular way foreach(User Userinchusers) { if(Nonduplicatelist3.exists (x=>x.name==user.name) = =false) {nonduplicatelist3.add (user); } } foreach(List<user> Listinch NewOBJECT[]{NONDUPLICATELIST1,NONDUPLICATELIST2,NONDUPLICATELIST3})//print out three elements of a list{Console.Write ("nonduplicatelist:\r\n"); foreach(User uinchlist) {Console.WriteLine ("\ t"+u.tostring ()); }} console.read (); } } classUser:iequatable<user>//inherit the IEquatable interface to implement the Equals method. List can use distinct to go to heavy { Public stringName {Get;Set; } stringaddress; PublicUser (string_name,string_address) {Name=_name; Address=_address; } Public Override stringToString () {return string. Format ("Name:{0},\taddress:{1}", name, address); } Public BOOLEquals (User other) {return This. Name = =Other.name; } Public Override intGetHashCode () {returnname. GetHashCode (); } } }
Original: http://blog.csdn.net/wangguanguo/article/details/46839793
C # List of three ways to Redo (go)