三种种方法"/>
List去重的三种种方法
List去重–C#
class List去重的方法//List如何去重{#region//自定义去重方法public static void Main() => useDistinctMethod();public static void diyMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person{ name= "李四" , password = "123456", age = 20 });list.Add(new Person{ name = "张三", password = "123456", age = 18 });list.Add(new Person{ name = "王五", password = "123456", age = 22 });list.Add(new Person{ name = "张三", password = "123456", age = 18 });// 去重操作List<Person> newList = new List<Person>(list.Count());list.ForEach(i=> {if (!newList.Contains(i)){ newList.Add(i);}});newList.ForEach(p => Console.WriteLine($"{ p.name },{ p.password },{ p.age }"));Console.ReadKey();}#endregion#region//用hashset唯一真值去重public static void useSetMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person { name = "李四", password = "123456", age = 20 });list.Add(new Person { name = "张三", password = "123456", age = 18 });list.Add(new Person { name = "王五", password = "123456", age = 22 });list.Add(new Person { name = "张三", password = "123456", age = 18 });// 去重操作HashSet<Person> newList = new HashSet<Person>(list);foreach (Person p in newList){Console.WriteLine($"{ p.name },{ p.password },{ p.age }");}Console.ReadKey();}#endregion#region//用Distinct去重public static void useDistinctMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person { name = "李四", password = "123456", age = 20 });list.Add(new Person { name = "张三", password = "123456", age = 18 });list.Add(new Person { name = "王五", password = "123456", age = 22 });list.Add(new Person { name = "张三", password = "123456", age = 18 });// 去重操作var newList = list.Distinct();foreach (Person p in newList){Console.WriteLine($"{ p.name },{ p.password },{ p.age }");}Console.ReadKey();}#endregion}struct Person{public String name { get; set; }public String password { get; set; }public int age { get; set; }}
更多推荐
List去重的三种种方法
发布评论