C# List去重的三种方法
2021-04-18 13:30
阅读:547
转载至:https://blog.csdn.net/wangguanguo/article/details/46839793
三种去重的方法
1、List中的元素实现IEquatabe接口,并提供Equals方法和GetHashCode方法。
2、使用表达式
users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i)
去重,这条语句返回结果只保留users这个List中重复的元素的第一个(name相等认为重复)。
3、使用循环,判断每个元素是否重复
[csharp] view plain copy
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace NonDuplicateList
- {
- class Program
- {
- static void Main(string[] args)
- {
- List
users = new List (); - users.Add(new User("张三", "永丰路299号"));
- users.Add(new User("张三", "上地西路8号"));//重复项,去重后将删掉
- users.Add(new User("李四", "海鹰路甲一号"));
- List
nonDuplicateList1 = users.Distinct().ToList();//通过User类的Equals实现去重 - List
nonDuplicateList2 = users.Where((x,i)=>users.FindIndex(z=>z.name == x.name) == i).ToList();//Lambda表达式去重 - List
nonDuplicateList3 = new List ();//通过循环方式去重 - foreach(User user in users)
- {
- if(nonDuplicateList3.Exists(x=>x.name==user.name) == false)
- {
- nonDuplicateList3.Add(user);
- }
- }
- foreach(List
list in new Object[]{nonDuplicateList1,nonDuplicateList2,nonDuplicateList3})//打印出三个List的元素 - {
- Console.Write("nonDuplicateList:\r\n");
- foreach(User u in list)
- {
- Console.WriteLine("\t" + u.ToString());
- }
- }
- Console.Read();
- }
- }
- class User:IEquatable
//继承IEquatable接口,实现Equals方法。List就可以使用Distinct去重 - {
- 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();
- }
- }
- }
上一篇:WPF转换器:时间转换为字符串
评论
亲,登录后才可以留言!