Reprint to: 46839793
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
[CSharp]View PlainCopy
- Using System;
- Using System.Collections.Generic;
- Using System.Linq;
- Namespace Nonduplicatelist
- {
- Class Program
- {
- static void Main (string[] args)
- {
- list<user> users = new list<user> ();
- Users. ADD (new User ("Zhang San", "Yongfeng road No. 299"));
- Users. ADD (new User ("Zhang San", "8th on West Road")); Duplicates, which will be deleted when the weight is removed.
- Users. ADD (new User ("John Doe", "Sea Eagle Road Armour One"));
- List<user> nonDuplicateList1 = users. Distinct (). ToList (); //Through the Equals of the user class to achieve the weight
- List<user> nonDuplicateList2 = users. Where ((x,i) =>users. FindIndex (Z=>z.name = = x.name) = = i). ToList (); //lambda expression de-weight
- list<user> nonDuplicateList3 = new list<user> (); To weigh in a circular way
- foreach (user user in users)
- {
- if (nonduplicatelist3.exists (x=>x.name==user.name) = = false)
- {
- Nonduplicatelist3.add (user);
- }
- }
- foreach (list<user> List in new OBJECT[]{NONDUPLICATELIST1,NONDUPLICATELIST2,NONDUPLICATELIST3}) //Print out three elements of list
- {
- Console.Write ("nonduplicatelist:\r\n");
- foreach (User u in list)
- {
- Console.WriteLine ("\ T" + u.tostring ());
- }
- }
- Console.read ();
- }
- }
- class user:iequatable<user>//inherits the IEquatable interface, implementing the Equals method. List can use distinct to go to heavy
- {
- public string name { get; set;}
- string Address;
- Public User (string _name, string _address)
- {
- name = _name;
- address = _address;
- }
- public Override string ToString ()
- {
- return string. Format ("Name:{0},\taddress:{1}", name, address);
- }
- Public bool Equals (User other)
- {
- return this.name = = Other.name;
- }
- public override int GetHashCode ()
- {
- return name. GetHashCode ();
- }
- }
- }
Three ways to remove weight from C # list